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,000 | pantsbuild/pants | src/python/pants/java/jar/jar_dependency_utils.py | M2Coordinate.copy | def copy(self, **replacements):
"""Returns a clone of this M2Coordinate with the given replacements kwargs overlaid."""
cls = type(self)
kwargs = {'org': self.org, 'name': self.name, 'ext': self.ext, 'classifier': self.classifier, 'rev': self.rev}
for key, val in replacements.items():
kwargs[key] = val
return cls(**kwargs) | python | def copy(self, **replacements):
cls = type(self)
kwargs = {'org': self.org, 'name': self.name, 'ext': self.ext, 'classifier': self.classifier, 'rev': self.rev}
for key, val in replacements.items():
kwargs[key] = val
return cls(**kwargs) | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"replacements",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"kwargs",
"=",
"{",
"'org'",
":",
"self",
".",
"org",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'ext'",
":",
"self",
".",
"ext",
","... | Returns a clone of this M2Coordinate with the given replacements kwargs overlaid. | [
"Returns",
"a",
"clone",
"of",
"this",
"M2Coordinate",
"with",
"the",
"given",
"replacements",
"kwargs",
"overlaid",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/jar/jar_dependency_utils.py#L168-L174 |
224,001 | pantsbuild/pants | src/python/pants/reporting/reporter.py | Reporter.handle_log | def handle_log(self, workunit, level, *msg_elements):
"""Handle a message logged by pants code.
level: One of the constants above.
Each element in msg_elements is either a message or a (message, detail) pair.
A subclass must show the message, but may choose to show the detail in some
sensible way (e.g., when the message text is clicked on in a browser).
This convenience implementation filters by log level and then delegates to do_handle_log.
"""
if level <= self.level_for_workunit(workunit, self.settings.log_level):
self.do_handle_log(workunit, level, *msg_elements) | python | def handle_log(self, workunit, level, *msg_elements):
if level <= self.level_for_workunit(workunit, self.settings.log_level):
self.do_handle_log(workunit, level, *msg_elements) | [
"def",
"handle_log",
"(",
"self",
",",
"workunit",
",",
"level",
",",
"*",
"msg_elements",
")",
":",
"if",
"level",
"<=",
"self",
".",
"level_for_workunit",
"(",
"workunit",
",",
"self",
".",
"settings",
".",
"log_level",
")",
":",
"self",
".",
"do_handl... | Handle a message logged by pants code.
level: One of the constants above.
Each element in msg_elements is either a message or a (message, detail) pair.
A subclass must show the message, but may choose to show the detail in some
sensible way (e.g., when the message text is clicked on in a browser).
This convenience implementation filters by log level and then delegates to do_handle_log. | [
"Handle",
"a",
"message",
"logged",
"by",
"pants",
"code",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/reporter.py#L54-L66 |
224,002 | pantsbuild/pants | src/python/pants/engine/round_engine.py | GoalExecutor.attempt | def attempt(self, explain):
"""Attempts to execute the goal's tasks in installed order.
:param bool explain: If ``True`` then the goal plan will be explained instead of being
executed.
"""
goal_workdir = os.path.join(self._context.options.for_global_scope().pants_workdir,
self._goal.name)
with self._context.new_workunit(name=self._goal.name, labels=[WorkUnitLabel.GOAL]):
for name, task_type in reversed(list(self._tasktypes_by_name.items())):
task_workdir = os.path.join(goal_workdir, name)
task = task_type(self._context, task_workdir)
log_config = WorkUnit.LogConfig(level=task.get_options().level, colors=task.get_options().colors)
with self._context.new_workunit(name=name, labels=[WorkUnitLabel.TASK], log_config=log_config):
if explain:
self._context.log.debug('Skipping execution of {} in explain mode'.format(name))
elif task.skip_execution:
self._context.log.info('Skipping {}'.format(name))
else:
task.execute()
if explain:
reversed_tasktypes_by_name = reversed(list(self._tasktypes_by_name.items()))
goal_to_task = ', '.join(
'{}->{}'.format(name, task_type.__name__) for name, task_type in reversed_tasktypes_by_name)
print('{goal} [{goal_to_task}]'.format(goal=self._goal.name, goal_to_task=goal_to_task)) | python | def attempt(self, explain):
goal_workdir = os.path.join(self._context.options.for_global_scope().pants_workdir,
self._goal.name)
with self._context.new_workunit(name=self._goal.name, labels=[WorkUnitLabel.GOAL]):
for name, task_type in reversed(list(self._tasktypes_by_name.items())):
task_workdir = os.path.join(goal_workdir, name)
task = task_type(self._context, task_workdir)
log_config = WorkUnit.LogConfig(level=task.get_options().level, colors=task.get_options().colors)
with self._context.new_workunit(name=name, labels=[WorkUnitLabel.TASK], log_config=log_config):
if explain:
self._context.log.debug('Skipping execution of {} in explain mode'.format(name))
elif task.skip_execution:
self._context.log.info('Skipping {}'.format(name))
else:
task.execute()
if explain:
reversed_tasktypes_by_name = reversed(list(self._tasktypes_by_name.items()))
goal_to_task = ', '.join(
'{}->{}'.format(name, task_type.__name__) for name, task_type in reversed_tasktypes_by_name)
print('{goal} [{goal_to_task}]'.format(goal=self._goal.name, goal_to_task=goal_to_task)) | [
"def",
"attempt",
"(",
"self",
",",
"explain",
")",
":",
"goal_workdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_context",
".",
"options",
".",
"for_global_scope",
"(",
")",
".",
"pants_workdir",
",",
"self",
".",
"_goal",
".",
"name",... | Attempts to execute the goal's tasks in installed order.
:param bool explain: If ``True`` then the goal plan will be explained instead of being
executed. | [
"Attempts",
"to",
"execute",
"the",
"goal",
"s",
"tasks",
"in",
"installed",
"order",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/round_engine.py#L31-L56 |
224,003 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/trailing_whitespace.py | TrailingWhitespace.build_exception_map | def build_exception_map(cls, tokens):
"""Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings.
"""
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.COMMENT, tokenize.STRING):
if token_start[0] == token_end[0]:
exception_ranges[token_start[0]].append((token_start[1], token_end[1]))
else:
exception_ranges[token_start[0]].append((token_start[1], sys.maxsize))
for line in range(token_start[0] + 1, token_end[0]):
exception_ranges[line].append((0, sys.maxsize))
exception_ranges[token_end[0]].append((0, token_end[1]))
return exception_ranges | python | def build_exception_map(cls, tokens):
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.COMMENT, tokenize.STRING):
if token_start[0] == token_end[0]:
exception_ranges[token_start[0]].append((token_start[1], token_end[1]))
else:
exception_ranges[token_start[0]].append((token_start[1], sys.maxsize))
for line in range(token_start[0] + 1, token_end[0]):
exception_ranges[line].append((0, sys.maxsize))
exception_ranges[token_end[0]].append((0, token_end[1]))
return exception_ranges | [
"def",
"build_exception_map",
"(",
"cls",
",",
"tokens",
")",
":",
"exception_ranges",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"token",
"in",
"tokens",
":",
"token_type",
",",
"_",
",",
"token_start",
",",
"token_end",
"=",
"token",
"[",
"0",
":",
"... | Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings. | [
"Generates",
"a",
"set",
"of",
"ranges",
"where",
"we",
"accept",
"trailing",
"slashes",
"specifically",
"within",
"comments",
"and",
"strings",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/trailing_whitespace.py#L24-L39 |
224,004 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py | GoWorkspaceTask.ensure_workspace | def ensure_workspace(self, target):
"""Ensures that an up-to-date Go workspace exists for the given target.
Creates any necessary symlinks to source files based on the target and its transitive
dependencies, and removes any symlinks which do not correspond to any needed dep.
"""
gopath = self.get_gopath(target)
for d in ('bin', 'pkg', 'src'):
safe_mkdir(os.path.join(gopath, d))
required_links = set()
for dep in target.closure():
if not isinstance(dep, GoTarget):
continue
if self.is_remote_lib(dep):
self._symlink_remote_lib(gopath, dep, required_links)
else:
self._symlink_local_src(gopath, dep, required_links)
self.remove_unused_links(os.path.join(gopath, 'src'), required_links) | python | def ensure_workspace(self, target):
gopath = self.get_gopath(target)
for d in ('bin', 'pkg', 'src'):
safe_mkdir(os.path.join(gopath, d))
required_links = set()
for dep in target.closure():
if not isinstance(dep, GoTarget):
continue
if self.is_remote_lib(dep):
self._symlink_remote_lib(gopath, dep, required_links)
else:
self._symlink_local_src(gopath, dep, required_links)
self.remove_unused_links(os.path.join(gopath, 'src'), required_links) | [
"def",
"ensure_workspace",
"(",
"self",
",",
"target",
")",
":",
"gopath",
"=",
"self",
".",
"get_gopath",
"(",
"target",
")",
"for",
"d",
"in",
"(",
"'bin'",
",",
"'pkg'",
",",
"'src'",
")",
":",
"safe_mkdir",
"(",
"os",
".",
"path",
".",
"join",
... | Ensures that an up-to-date Go workspace exists for the given target.
Creates any necessary symlinks to source files based on the target and its transitive
dependencies, and removes any symlinks which do not correspond to any needed dep. | [
"Ensures",
"that",
"an",
"up",
"-",
"to",
"-",
"date",
"Go",
"workspace",
"exists",
"for",
"the",
"given",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py#L36-L53 |
224,005 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py | GoWorkspaceTask.remove_unused_links | def remove_unused_links(dirpath, required_links):
"""Recursively remove any links in dirpath which are not contained in required_links.
:param str dirpath: Absolute path of directory to search.
:param container required_links: Container of "in use" links which should not be removed,
where each link is an absolute path.
"""
for root, dirs, files in os.walk(dirpath):
for p in chain(dirs, files):
p = os.path.join(root, p)
if os.path.islink(p) and p not in required_links:
os.unlink(p) | python | def remove_unused_links(dirpath, required_links):
for root, dirs, files in os.walk(dirpath):
for p in chain(dirs, files):
p = os.path.join(root, p)
if os.path.islink(p) and p not in required_links:
os.unlink(p) | [
"def",
"remove_unused_links",
"(",
"dirpath",
",",
"required_links",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirpath",
")",
":",
"for",
"p",
"in",
"chain",
"(",
"dirs",
",",
"files",
")",
":",
"p",
"=",
"o... | Recursively remove any links in dirpath which are not contained in required_links.
:param str dirpath: Absolute path of directory to search.
:param container required_links: Container of "in use" links which should not be removed,
where each link is an absolute path. | [
"Recursively",
"remove",
"any",
"links",
"in",
"dirpath",
"which",
"are",
"not",
"contained",
"in",
"required_links",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py#L56-L67 |
224,006 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py | GoWorkspaceTask._symlink_local_src | def _symlink_local_src(self, gopath, go_local_src, required_links):
"""Creates symlinks from the given gopath to the source files of the given local package.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the symlinks to the source files to required_links.
"""
source_list = [os.path.join(get_buildroot(), src)
for src in go_local_src.sources_relative_to_buildroot()]
rel_list = go_local_src.sources_relative_to_target_base()
source_iter = zip(source_list, rel_list)
return self._symlink_lib(gopath, go_local_src, source_iter, required_links) | python | def _symlink_local_src(self, gopath, go_local_src, required_links):
source_list = [os.path.join(get_buildroot(), src)
for src in go_local_src.sources_relative_to_buildroot()]
rel_list = go_local_src.sources_relative_to_target_base()
source_iter = zip(source_list, rel_list)
return self._symlink_lib(gopath, go_local_src, source_iter, required_links) | [
"def",
"_symlink_local_src",
"(",
"self",
",",
"gopath",
",",
"go_local_src",
",",
"required_links",
")",
":",
"source_list",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"get_buildroot",
"(",
")",
",",
"src",
")",
"for",
"src",
"in",
"go_local_src",
"... | Creates symlinks from the given gopath to the source files of the given local package.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the symlinks to the source files to required_links. | [
"Creates",
"symlinks",
"from",
"the",
"given",
"gopath",
"to",
"the",
"source",
"files",
"of",
"the",
"given",
"local",
"package",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py#L69-L81 |
224,007 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py | GoWorkspaceTask._symlink_remote_lib | def _symlink_remote_lib(self, gopath, go_remote_lib, required_links):
"""Creates symlinks from the given gopath to the source files of the given remote lib.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the symlinks to the source files to required_links.
"""
def source_iter():
remote_lib_source_dir = self.context.products.get_data('go_remote_lib_src')[go_remote_lib]
for path in os.listdir(remote_lib_source_dir):
remote_src = os.path.join(remote_lib_source_dir, path)
# We grab any file since a go package might have .go, .c, .cc, etc files - all needed for
# installation.
if os.path.isfile(remote_src):
yield (remote_src, os.path.basename(path))
return self._symlink_lib(gopath, go_remote_lib, source_iter(), required_links) | python | def _symlink_remote_lib(self, gopath, go_remote_lib, required_links):
def source_iter():
remote_lib_source_dir = self.context.products.get_data('go_remote_lib_src')[go_remote_lib]
for path in os.listdir(remote_lib_source_dir):
remote_src = os.path.join(remote_lib_source_dir, path)
# We grab any file since a go package might have .go, .c, .cc, etc files - all needed for
# installation.
if os.path.isfile(remote_src):
yield (remote_src, os.path.basename(path))
return self._symlink_lib(gopath, go_remote_lib, source_iter(), required_links) | [
"def",
"_symlink_remote_lib",
"(",
"self",
",",
"gopath",
",",
"go_remote_lib",
",",
"required_links",
")",
":",
"def",
"source_iter",
"(",
")",
":",
"remote_lib_source_dir",
"=",
"self",
".",
"context",
".",
"products",
".",
"get_data",
"(",
"'go_remote_lib_src... | Creates symlinks from the given gopath to the source files of the given remote lib.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the symlinks to the source files to required_links. | [
"Creates",
"symlinks",
"from",
"the",
"given",
"gopath",
"to",
"the",
"source",
"files",
"of",
"the",
"given",
"remote",
"lib",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py#L83-L99 |
224,008 | pantsbuild/pants | src/python/pants/help/scope_info_iterator.py | ScopeInfoIterator.iterate | def iterate(self, scopes):
"""Yields ScopeInfo instances for the specified scopes, plus relevant related scopes.
Relevant scopes are:
- All tasks in a requested goal.
- All subsystems tied to a request scope.
Yields in a sensible order: Sorted by scope, but with subsystems tied to a request scope
following that scope, e.g.,
goal1
goal1.task11
subsys.goal1.task11
goal1.task12
goal2.task21
...
"""
scope_infos = [self._scope_to_info[s] for s in self._expand_tasks(scopes)]
if scope_infos:
for scope_info in self._expand_subsystems(scope_infos):
yield scope_info | python | def iterate(self, scopes):
scope_infos = [self._scope_to_info[s] for s in self._expand_tasks(scopes)]
if scope_infos:
for scope_info in self._expand_subsystems(scope_infos):
yield scope_info | [
"def",
"iterate",
"(",
"self",
",",
"scopes",
")",
":",
"scope_infos",
"=",
"[",
"self",
".",
"_scope_to_info",
"[",
"s",
"]",
"for",
"s",
"in",
"self",
".",
"_expand_tasks",
"(",
"scopes",
")",
"]",
"if",
"scope_infos",
":",
"for",
"scope_info",
"in",... | Yields ScopeInfo instances for the specified scopes, plus relevant related scopes.
Relevant scopes are:
- All tasks in a requested goal.
- All subsystems tied to a request scope.
Yields in a sensible order: Sorted by scope, but with subsystems tied to a request scope
following that scope, e.g.,
goal1
goal1.task11
subsys.goal1.task11
goal1.task12
goal2.task21
... | [
"Yields",
"ScopeInfo",
"instances",
"for",
"the",
"specified",
"scopes",
"plus",
"relevant",
"related",
"scopes",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/help/scope_info_iterator.py#L25-L45 |
224,009 | pantsbuild/pants | src/python/pants/help/scope_info_iterator.py | ScopeInfoIterator._expand_tasks | def _expand_tasks(self, scopes):
"""Add all tasks in any requested goals.
Returns the requested scopes, plus the added tasks, sorted by scope name.
"""
expanded_scopes = set(scopes)
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.TASK:
outer = enclosing_scope(scope)
while outer != GLOBAL_SCOPE:
if outer in expanded_scopes:
expanded_scopes.add(scope)
break
outer = enclosing_scope(outer)
return sorted(expanded_scopes) | python | def _expand_tasks(self, scopes):
expanded_scopes = set(scopes)
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.TASK:
outer = enclosing_scope(scope)
while outer != GLOBAL_SCOPE:
if outer in expanded_scopes:
expanded_scopes.add(scope)
break
outer = enclosing_scope(outer)
return sorted(expanded_scopes) | [
"def",
"_expand_tasks",
"(",
"self",
",",
"scopes",
")",
":",
"expanded_scopes",
"=",
"set",
"(",
"scopes",
")",
"for",
"scope",
",",
"info",
"in",
"self",
".",
"_scope_to_info",
".",
"items",
"(",
")",
":",
"if",
"info",
".",
"category",
"==",
"ScopeI... | Add all tasks in any requested goals.
Returns the requested scopes, plus the added tasks, sorted by scope name. | [
"Add",
"all",
"tasks",
"in",
"any",
"requested",
"goals",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/help/scope_info_iterator.py#L47-L61 |
224,010 | pantsbuild/pants | src/python/pants/help/scope_info_iterator.py | ScopeInfoIterator._expand_subsystems | def _expand_subsystems(self, scope_infos):
"""Add all subsystems tied to a scope, right after that scope."""
# Get non-global subsystem dependencies of the specified subsystem client.
def subsys_deps(subsystem_client_cls):
for dep in subsystem_client_cls.subsystem_dependencies_iter():
if dep.scope != GLOBAL_SCOPE:
yield self._scope_to_info[dep.options_scope]
for x in subsys_deps(dep.subsystem_cls):
yield x
for scope_info in scope_infos:
yield scope_info
if scope_info.optionable_cls is not None:
# We don't currently subclass GlobalOptionsRegistrar, and I can't think of any reason why
# we would, but might as well be robust.
if issubclass(scope_info.optionable_cls, GlobalOptionsRegistrar):
# We were asked for global help, so also yield for all global subsystems.
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.SUBSYSTEM and enclosing_scope(scope) == GLOBAL_SCOPE:
yield info
for subsys_dep in subsys_deps(info.optionable_cls):
yield subsys_dep
elif issubclass(scope_info.optionable_cls, SubsystemClientMixin):
for subsys_dep in subsys_deps(scope_info.optionable_cls):
yield subsys_dep | python | def _expand_subsystems(self, scope_infos):
# Get non-global subsystem dependencies of the specified subsystem client.
def subsys_deps(subsystem_client_cls):
for dep in subsystem_client_cls.subsystem_dependencies_iter():
if dep.scope != GLOBAL_SCOPE:
yield self._scope_to_info[dep.options_scope]
for x in subsys_deps(dep.subsystem_cls):
yield x
for scope_info in scope_infos:
yield scope_info
if scope_info.optionable_cls is not None:
# We don't currently subclass GlobalOptionsRegistrar, and I can't think of any reason why
# we would, but might as well be robust.
if issubclass(scope_info.optionable_cls, GlobalOptionsRegistrar):
# We were asked for global help, so also yield for all global subsystems.
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.SUBSYSTEM and enclosing_scope(scope) == GLOBAL_SCOPE:
yield info
for subsys_dep in subsys_deps(info.optionable_cls):
yield subsys_dep
elif issubclass(scope_info.optionable_cls, SubsystemClientMixin):
for subsys_dep in subsys_deps(scope_info.optionable_cls):
yield subsys_dep | [
"def",
"_expand_subsystems",
"(",
"self",
",",
"scope_infos",
")",
":",
"# Get non-global subsystem dependencies of the specified subsystem client.",
"def",
"subsys_deps",
"(",
"subsystem_client_cls",
")",
":",
"for",
"dep",
"in",
"subsystem_client_cls",
".",
"subsystem_depen... | Add all subsystems tied to a scope, right after that scope. | [
"Add",
"all",
"subsystems",
"tied",
"to",
"a",
"scope",
"right",
"after",
"that",
"scope",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/help/scope_info_iterator.py#L63-L88 |
224,011 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvmdoc_gen.py | JvmdocGen.generate_doc | def generate_doc(self, language_predicate, create_jvmdoc_command):
"""
Generate an execute method given a language predicate and command to create documentation
language_predicate: a function that accepts a target and returns True if the target is of that
language
create_jvmdoc_command: (classpath, directory, *targets) -> command (string) that will generate
documentation documentation for targets
"""
catalog = self.context.products.isrequired(self.jvmdoc().product_type)
if catalog and self.combined:
raise TaskError(
'Cannot provide {} target mappings for combined output'.format(self.jvmdoc().product_type))
def docable(target):
if not language_predicate(target):
self.context.log.debug('Skipping [{}] because it is does not pass the language predicate'.format(target.address.spec))
return False
if not self._include_codegen and target.is_synthetic:
self.context.log.debug('Skipping [{}] because it is a synthetic target'.format(target.address.spec))
return False
for pattern in self._exclude_patterns:
if pattern.search(target.address.spec):
self.context.log.debug(
"Skipping [{}] because it matches exclude pattern '{}'".format(target.address.spec, pattern.pattern))
return False
return True
targets = self.get_targets(predicate=docable)
if not targets:
return
with self.invalidated(targets, invalidate_dependents=self.combined) as invalidation_check:
def find_invalid_targets():
invalid_targets = set()
for vt in invalidation_check.invalid_vts:
invalid_targets.update(vt.targets)
return invalid_targets
invalid_targets = list(find_invalid_targets())
if invalid_targets:
if self.combined:
self._generate_combined(targets, create_jvmdoc_command)
else:
self._generate_individual(invalid_targets, create_jvmdoc_command)
if self.open and self.combined:
try:
desktop.ui_open(os.path.join(self.workdir, 'combined', 'index.html'))
except desktop.OpenError as e:
raise TaskError(e)
if catalog:
for target in targets:
gendir = self._gendir(target)
jvmdocs = []
for root, dirs, files in safe_walk(gendir):
jvmdocs.extend(os.path.relpath(os.path.join(root, f), gendir) for f in files)
self.context.products.get(self.jvmdoc().product_type).add(target, gendir, jvmdocs) | python | def generate_doc(self, language_predicate, create_jvmdoc_command):
catalog = self.context.products.isrequired(self.jvmdoc().product_type)
if catalog and self.combined:
raise TaskError(
'Cannot provide {} target mappings for combined output'.format(self.jvmdoc().product_type))
def docable(target):
if not language_predicate(target):
self.context.log.debug('Skipping [{}] because it is does not pass the language predicate'.format(target.address.spec))
return False
if not self._include_codegen and target.is_synthetic:
self.context.log.debug('Skipping [{}] because it is a synthetic target'.format(target.address.spec))
return False
for pattern in self._exclude_patterns:
if pattern.search(target.address.spec):
self.context.log.debug(
"Skipping [{}] because it matches exclude pattern '{}'".format(target.address.spec, pattern.pattern))
return False
return True
targets = self.get_targets(predicate=docable)
if not targets:
return
with self.invalidated(targets, invalidate_dependents=self.combined) as invalidation_check:
def find_invalid_targets():
invalid_targets = set()
for vt in invalidation_check.invalid_vts:
invalid_targets.update(vt.targets)
return invalid_targets
invalid_targets = list(find_invalid_targets())
if invalid_targets:
if self.combined:
self._generate_combined(targets, create_jvmdoc_command)
else:
self._generate_individual(invalid_targets, create_jvmdoc_command)
if self.open and self.combined:
try:
desktop.ui_open(os.path.join(self.workdir, 'combined', 'index.html'))
except desktop.OpenError as e:
raise TaskError(e)
if catalog:
for target in targets:
gendir = self._gendir(target)
jvmdocs = []
for root, dirs, files in safe_walk(gendir):
jvmdocs.extend(os.path.relpath(os.path.join(root, f), gendir) for f in files)
self.context.products.get(self.jvmdoc().product_type).add(target, gendir, jvmdocs) | [
"def",
"generate_doc",
"(",
"self",
",",
"language_predicate",
",",
"create_jvmdoc_command",
")",
":",
"catalog",
"=",
"self",
".",
"context",
".",
"products",
".",
"isrequired",
"(",
"self",
".",
"jvmdoc",
"(",
")",
".",
"product_type",
")",
"if",
"catalog"... | Generate an execute method given a language predicate and command to create documentation
language_predicate: a function that accepts a target and returns True if the target is of that
language
create_jvmdoc_command: (classpath, directory, *targets) -> command (string) that will generate
documentation documentation for targets | [
"Generate",
"an",
"execute",
"method",
"given",
"a",
"language",
"predicate",
"and",
"command",
"to",
"create",
"documentation"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvmdoc_gen.py#L82-L140 |
224,012 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_task.py | JvmTask.classpath | def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None,
include_scopes=None):
"""Builds a transitive classpath for the given targets.
Optionally includes a classpath prefix or building from a non-default classpath product.
:param targets: the targets for which to build the transitive classpath.
:param classpath_prefix: optional additional entries to prepend to the classpath.
:param classpath_product: an optional ClasspathProduct from which to build the classpath. if not
specified, the runtime_classpath will be used.
:param :class:`pants.build_graph.target_scopes.Scope` exclude_scopes: Exclude targets which
have at least one of these scopes on the classpath.
:param :class:`pants.build_graph.target_scopes.Scope` include_scopes: Only include targets which
have at least one of these scopes on the classpath. Defaults to Scopes.JVM_RUNTIME_SCOPES.
:return: a list of classpath strings.
"""
include_scopes = Scopes.JVM_RUNTIME_SCOPES if include_scopes is None else include_scopes
classpath_product = classpath_product or self.context.products.get_data('runtime_classpath')
closure = BuildGraph.closure(targets, bfs=True, include_scopes=include_scopes,
exclude_scopes=exclude_scopes, respect_intransitive=True)
classpath_for_targets = ClasspathUtil.classpath(closure, classpath_product, self.confs)
classpath = list(classpath_prefix or ())
classpath.extend(classpath_for_targets)
return classpath | python | def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None,
include_scopes=None):
include_scopes = Scopes.JVM_RUNTIME_SCOPES if include_scopes is None else include_scopes
classpath_product = classpath_product or self.context.products.get_data('runtime_classpath')
closure = BuildGraph.closure(targets, bfs=True, include_scopes=include_scopes,
exclude_scopes=exclude_scopes, respect_intransitive=True)
classpath_for_targets = ClasspathUtil.classpath(closure, classpath_product, self.confs)
classpath = list(classpath_prefix or ())
classpath.extend(classpath_for_targets)
return classpath | [
"def",
"classpath",
"(",
"self",
",",
"targets",
",",
"classpath_prefix",
"=",
"None",
",",
"classpath_product",
"=",
"None",
",",
"exclude_scopes",
"=",
"None",
",",
"include_scopes",
"=",
"None",
")",
":",
"include_scopes",
"=",
"Scopes",
".",
"JVM_RUNTIME_S... | Builds a transitive classpath for the given targets.
Optionally includes a classpath prefix or building from a non-default classpath product.
:param targets: the targets for which to build the transitive classpath.
:param classpath_prefix: optional additional entries to prepend to the classpath.
:param classpath_product: an optional ClasspathProduct from which to build the classpath. if not
specified, the runtime_classpath will be used.
:param :class:`pants.build_graph.target_scopes.Scope` exclude_scopes: Exclude targets which
have at least one of these scopes on the classpath.
:param :class:`pants.build_graph.target_scopes.Scope` include_scopes: Only include targets which
have at least one of these scopes on the classpath. Defaults to Scopes.JVM_RUNTIME_SCOPES.
:return: a list of classpath strings. | [
"Builds",
"a",
"transitive",
"classpath",
"for",
"the",
"given",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_task.py#L49-L73 |
224,013 | pantsbuild/pants | src/python/pants/util/fileutil.py | atomic_copy | def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp_dst.name)
os.chmod(tmp_dst.name, os.stat(src).st_mode)
os.rename(tmp_dst.name, dst) | python | def atomic_copy(src, dst):
with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp_dst.name)
os.chmod(tmp_dst.name, os.stat(src).st_mode)
os.rename(tmp_dst.name, dst) | [
"def",
"atomic_copy",
"(",
"src",
",",
"dst",
")",
":",
"with",
"temporary_file",
"(",
"root_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dst",
")",
")",
"as",
"tmp_dst",
":",
"shutil",
".",
"copyfile",
"(",
"src",
",",
"tmp_dst",
".",
"name",... | Copy the file src to dst, overwriting dst atomically. | [
"Copy",
"the",
"file",
"src",
"to",
"dst",
"overwriting",
"dst",
"atomically",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/fileutil.py#L18-L23 |
224,014 | pantsbuild/pants | src/python/pants/util/fileutil.py | safe_temp_edit | def safe_temp_edit(filename):
"""Safely modify a file within context that automatically reverts any changes afterwards
The file mutatation occurs in place. The file is backed up in a temporary file before edits
occur and when the context is closed, the mutated file is discarded and replaced with the backup.
WARNING: There may be a chance that the file may not be restored and this method should be used
carefully with the known risk.
"""
with temporary_file() as tmp_file:
try:
shutil.copyfile(filename, tmp_file.name)
yield filename
finally:
shutil.copyfile(tmp_file.name, filename) | python | def safe_temp_edit(filename):
with temporary_file() as tmp_file:
try:
shutil.copyfile(filename, tmp_file.name)
yield filename
finally:
shutil.copyfile(tmp_file.name, filename) | [
"def",
"safe_temp_edit",
"(",
"filename",
")",
":",
"with",
"temporary_file",
"(",
")",
"as",
"tmp_file",
":",
"try",
":",
"shutil",
".",
"copyfile",
"(",
"filename",
",",
"tmp_file",
".",
"name",
")",
"yield",
"filename",
"finally",
":",
"shutil",
".",
... | Safely modify a file within context that automatically reverts any changes afterwards
The file mutatation occurs in place. The file is backed up in a temporary file before edits
occur and when the context is closed, the mutated file is discarded and replaced with the backup.
WARNING: There may be a chance that the file may not be restored and this method should be used
carefully with the known risk. | [
"Safely",
"modify",
"a",
"file",
"within",
"context",
"that",
"automatically",
"reverts",
"any",
"changes",
"afterwards"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/fileutil.py#L27-L41 |
224,015 | pantsbuild/pants | src/python/pants/util/fileutil.py | create_size_estimators | def create_size_estimators():
"""Create a dict of name to a function that returns an estimated size for a given target.
The estimated size is used to build the largest targets first (subject to dependency constraints).
Choose 'random' to choose random sizes for each target, which may be useful for distributed
builds.
:returns: Dict of a name to a function that returns an estimated size.
"""
def line_count(filename):
with open(filename, 'rb') as fh:
return sum(1 for line in fh)
return {
'linecount': lambda srcs: sum(line_count(src) for src in srcs),
'filecount': lambda srcs: len(srcs),
'filesize': lambda srcs: sum(os.path.getsize(src) for src in srcs),
'nosize': lambda srcs: 0,
'random': lambda srcs: random.randint(0, 10000),
} | python | def create_size_estimators():
def line_count(filename):
with open(filename, 'rb') as fh:
return sum(1 for line in fh)
return {
'linecount': lambda srcs: sum(line_count(src) for src in srcs),
'filecount': lambda srcs: len(srcs),
'filesize': lambda srcs: sum(os.path.getsize(src) for src in srcs),
'nosize': lambda srcs: 0,
'random': lambda srcs: random.randint(0, 10000),
} | [
"def",
"create_size_estimators",
"(",
")",
":",
"def",
"line_count",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fh",
":",
"return",
"sum",
"(",
"1",
"for",
"line",
"in",
"fh",
")",
"return",
"{",
"'linecount'",... | Create a dict of name to a function that returns an estimated size for a given target.
The estimated size is used to build the largest targets first (subject to dependency constraints).
Choose 'random' to choose random sizes for each target, which may be useful for distributed
builds.
:returns: Dict of a name to a function that returns an estimated size. | [
"Create",
"a",
"dict",
"of",
"name",
"to",
"a",
"function",
"that",
"returns",
"an",
"estimated",
"size",
"for",
"a",
"given",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/fileutil.py#L44-L61 |
224,016 | pantsbuild/pants | src/python/pants/engine/isolated_process.py | fallible_to_exec_result_or_raise | def fallible_to_exec_result_or_raise(fallible_result, request):
"""Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error."""
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
fallible_result.stdout,
fallible_result.stderr,
fallible_result.output_directory_digest
)
else:
raise ProcessExecutionFailure(
fallible_result.exit_code,
fallible_result.stdout,
fallible_result.stderr,
request.description
) | python | def fallible_to_exec_result_or_raise(fallible_result, request):
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
fallible_result.stdout,
fallible_result.stderr,
fallible_result.output_directory_digest
)
else:
raise ProcessExecutionFailure(
fallible_result.exit_code,
fallible_result.stdout,
fallible_result.stderr,
request.description
) | [
"def",
"fallible_to_exec_result_or_raise",
"(",
"fallible_result",
",",
"request",
")",
":",
"if",
"fallible_result",
".",
"exit_code",
"==",
"0",
":",
"return",
"ExecuteProcessResult",
"(",
"fallible_result",
".",
"stdout",
",",
"fallible_result",
".",
"stderr",
",... | Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error. | [
"Converts",
"a",
"FallibleExecuteProcessResult",
"to",
"a",
"ExecuteProcessResult",
"or",
"raises",
"an",
"error",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/isolated_process.py#L113-L128 |
224,017 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | PythonFile.parse | def parse(cls, filename, root=None):
"""Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path.
"""
if root is not None:
if os.path.isabs(filename):
raise ValueError("filename must be a relative path if root is specified")
full_filename = os.path.join(root, filename)
else:
full_filename = filename
with io.open(full_filename, 'rb') as fp:
blob = fp.read()
tree = cls._parse(blob, filename)
return cls(blob=blob, tree=tree, root=root, filename=filename) | python | def parse(cls, filename, root=None):
if root is not None:
if os.path.isabs(filename):
raise ValueError("filename must be a relative path if root is specified")
full_filename = os.path.join(root, filename)
else:
full_filename = filename
with io.open(full_filename, 'rb') as fp:
blob = fp.read()
tree = cls._parse(blob, filename)
return cls(blob=blob, tree=tree, root=root, filename=filename) | [
"def",
"parse",
"(",
"cls",
",",
"filename",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"\"filename must be a relative path if ... | Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path. | [
"Parses",
"the",
"file",
"at",
"filename",
"and",
"returns",
"a",
"PythonFile",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L128-L145 |
224,018 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | PythonFile.translate_logical_line | def translate_logical_line(start, end, contents, indent_stack, endmarker=False):
"""Translate raw contents to logical lines"""
# Remove leading blank lines.
while contents[0] == '\n':
start += 1
contents.pop(0)
# Remove trailing blank lines.
while contents[-1] == '\n':
end -= 1
contents.pop()
indent = len(indent_stack[-1]) if indent_stack else 0
if endmarker:
indent = len(contents[0])
return start, end + 1, indent | python | def translate_logical_line(start, end, contents, indent_stack, endmarker=False):
# Remove leading blank lines.
while contents[0] == '\n':
start += 1
contents.pop(0)
# Remove trailing blank lines.
while contents[-1] == '\n':
end -= 1
contents.pop()
indent = len(indent_stack[-1]) if indent_stack else 0
if endmarker:
indent = len(contents[0])
return start, end + 1, indent | [
"def",
"translate_logical_line",
"(",
"start",
",",
"end",
",",
"contents",
",",
"indent_stack",
",",
"endmarker",
"=",
"False",
")",
":",
"# Remove leading blank lines.",
"while",
"contents",
"[",
"0",
"]",
"==",
"'\\n'",
":",
"start",
"+=",
"1",
"contents",
... | Translate raw contents to logical lines | [
"Translate",
"raw",
"contents",
"to",
"logical",
"lines"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L176-L190 |
224,019 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | PythonFile.line_range | def line_range(self, line_number):
"""Return a slice for the given line number"""
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.')
if line_number not in self.logical_lines:
return slice(line_number, line_number + 1)
else:
start, stop, _ = self.logical_lines[line_number]
return slice(start, stop) | python | def line_range(self, line_number):
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.')
if line_number not in self.logical_lines:
return slice(line_number, line_number + 1)
else:
start, stop, _ = self.logical_lines[line_number]
return slice(start, stop) | [
"def",
"line_range",
"(",
"self",
",",
"line_number",
")",
":",
"if",
"line_number",
"<=",
"0",
"or",
"line_number",
">",
"len",
"(",
"self",
".",
"lines",
")",
":",
"raise",
"IndexError",
"(",
"'NOTE: Python file line numbers are offset by 1.'",
")",
"if",
"l... | Return a slice for the given line number | [
"Return",
"a",
"slice",
"for",
"the",
"given",
"line",
"number"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L218-L227 |
224,020 | pantsbuild/pants | src/python/pants/backend/native/tasks/native_task.py | NativeTask.strict_deps_for_target | def strict_deps_for_target(self, target, predicate=None):
"""Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'.
If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will
only be able to see their immediate dependencies declared in the BUILD file. The 'strict_deps'
setting is obtained from the result of `get_compile_settings()`.
NB: This includes the current target in the result.
"""
if self._native_build_settings.get_strict_deps_value_for_target(target):
strict_deps = target.strict_dependencies(DependencyContext())
if predicate:
filtered_deps = list(filter(predicate, strict_deps))
else:
filtered_deps = strict_deps
deps = [target] + filtered_deps
else:
deps = self.context.build_graph.transitive_subgraph_of_addresses(
[target.address], predicate=predicate)
# Filter out the beginning target depending on whether it matches the predicate.
# TODO: There should be a cleaner way to do this.
deps = filter(predicate, deps)
return deps | python | def strict_deps_for_target(self, target, predicate=None):
if self._native_build_settings.get_strict_deps_value_for_target(target):
strict_deps = target.strict_dependencies(DependencyContext())
if predicate:
filtered_deps = list(filter(predicate, strict_deps))
else:
filtered_deps = strict_deps
deps = [target] + filtered_deps
else:
deps = self.context.build_graph.transitive_subgraph_of_addresses(
[target.address], predicate=predicate)
# Filter out the beginning target depending on whether it matches the predicate.
# TODO: There should be a cleaner way to do this.
deps = filter(predicate, deps)
return deps | [
"def",
"strict_deps_for_target",
"(",
"self",
",",
"target",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"_native_build_settings",
".",
"get_strict_deps_value_for_target",
"(",
"target",
")",
":",
"strict_deps",
"=",
"target",
".",
"strict_dependen... | Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'.
If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will
only be able to see their immediate dependencies declared in the BUILD file. The 'strict_deps'
setting is obtained from the result of `get_compile_settings()`.
NB: This includes the current target in the result. | [
"Get",
"the",
"dependencies",
"of",
"target",
"filtered",
"by",
"predicate",
"accounting",
"for",
"strict_deps",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_task.py#L118-L142 |
224,021 | pantsbuild/pants | src/python/pants/backend/codegen/antlr/java/antlr_java_gen.py | AntlrJavaGen._rearrange_output_for_package | def _rearrange_output_for_package(self, target_workdir, java_package):
"""Rearrange the output files to match a standard Java structure.
Antlr emits a directory structure based on the relative path provided
for the grammar file. If the source root of the file is different from
the Pants build root, then the Java files end up with undesired parent
directories.
"""
package_dir_rel = java_package.replace('.', os.path.sep)
package_dir = os.path.join(target_workdir, package_dir_rel)
safe_mkdir(package_dir)
for root, dirs, files in safe_walk(target_workdir):
if root == package_dir_rel:
# This path is already in the correct location
continue
for f in files:
os.rename(
os.path.join(root, f),
os.path.join(package_dir, f)
)
# Remove any empty directories that were left behind
for root, dirs, files in safe_walk(target_workdir, topdown = False):
for d in dirs:
full_dir = os.path.join(root, d)
if not os.listdir(full_dir):
os.rmdir(full_dir) | python | def _rearrange_output_for_package(self, target_workdir, java_package):
package_dir_rel = java_package.replace('.', os.path.sep)
package_dir = os.path.join(target_workdir, package_dir_rel)
safe_mkdir(package_dir)
for root, dirs, files in safe_walk(target_workdir):
if root == package_dir_rel:
# This path is already in the correct location
continue
for f in files:
os.rename(
os.path.join(root, f),
os.path.join(package_dir, f)
)
# Remove any empty directories that were left behind
for root, dirs, files in safe_walk(target_workdir, topdown = False):
for d in dirs:
full_dir = os.path.join(root, d)
if not os.listdir(full_dir):
os.rmdir(full_dir) | [
"def",
"_rearrange_output_for_package",
"(",
"self",
",",
"target_workdir",
",",
"java_package",
")",
":",
"package_dir_rel",
"=",
"java_package",
".",
"replace",
"(",
"'.'",
",",
"os",
".",
"path",
".",
"sep",
")",
"package_dir",
"=",
"os",
".",
"path",
"."... | Rearrange the output files to match a standard Java structure.
Antlr emits a directory structure based on the relative path provided
for the grammar file. If the source root of the file is different from
the Pants build root, then the Java files end up with undesired parent
directories. | [
"Rearrange",
"the",
"output",
"files",
"to",
"match",
"a",
"standard",
"Java",
"structure",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/antlr/java/antlr_java_gen.py#L129-L155 |
224,022 | pantsbuild/pants | src/python/pants/backend/codegen/antlr/java/antlr_java_gen.py | AntlrJavaGen._scrub_generated_timestamps | def _scrub_generated_timestamps(self, target_workdir):
"""Remove the first line of comment from each file if it contains a timestamp."""
for root, _, filenames in safe_walk(target_workdir):
for filename in filenames:
source = os.path.join(root, filename)
with open(source, 'r') as f:
lines = f.readlines()
if len(lines) < 1:
return
with open(source, 'w') as f:
if not self._COMMENT_WITH_TIMESTAMP_RE.match(lines[0]):
f.write(lines[0])
for line in lines[1:]:
f.write(line) | python | def _scrub_generated_timestamps(self, target_workdir):
for root, _, filenames in safe_walk(target_workdir):
for filename in filenames:
source = os.path.join(root, filename)
with open(source, 'r') as f:
lines = f.readlines()
if len(lines) < 1:
return
with open(source, 'w') as f:
if not self._COMMENT_WITH_TIMESTAMP_RE.match(lines[0]):
f.write(lines[0])
for line in lines[1:]:
f.write(line) | [
"def",
"_scrub_generated_timestamps",
"(",
"self",
",",
"target_workdir",
")",
":",
"for",
"root",
",",
"_",
",",
"filenames",
"in",
"safe_walk",
"(",
"target_workdir",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"source",
"=",
"os",
".",
"path",
... | Remove the first line of comment from each file if it contains a timestamp. | [
"Remove",
"the",
"first",
"line",
"of",
"comment",
"from",
"each",
"file",
"if",
"it",
"contains",
"a",
"timestamp",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/antlr/java/antlr_java_gen.py#L157-L171 |
224,023 | pantsbuild/pants | src/python/pants/backend/native/subsystems/native_toolchain.py | LinkerWrapperMixin.for_compiler | def for_compiler(self, compiler, platform):
"""Return a Linker object which is intended to be compatible with the given `compiler`."""
return (self.linker
# TODO(#6143): describe why the compiler needs to be first on the PATH!
.sequence(compiler, exclude_list_fields=['extra_args', 'path_entries'])
.prepend_field('path_entries', compiler.path_entries)
.copy(exe_filename=compiler.exe_filename)) | python | def for_compiler(self, compiler, platform):
return (self.linker
# TODO(#6143): describe why the compiler needs to be first on the PATH!
.sequence(compiler, exclude_list_fields=['extra_args', 'path_entries'])
.prepend_field('path_entries', compiler.path_entries)
.copy(exe_filename=compiler.exe_filename)) | [
"def",
"for_compiler",
"(",
"self",
",",
"compiler",
",",
"platform",
")",
":",
"return",
"(",
"self",
".",
"linker",
"# TODO(#6143): describe why the compiler needs to be first on the PATH!",
".",
"sequence",
"(",
"compiler",
",",
"exclude_list_fields",
"=",
"[",
"'e... | Return a Linker object which is intended to be compatible with the given `compiler`. | [
"Return",
"a",
"Linker",
"object",
"which",
"is",
"intended",
"to",
"be",
"compatible",
"with",
"the",
"given",
"compiler",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/subsystems/native_toolchain.py#L74-L80 |
224,024 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/import_order.py | ImportOrder.is_module_on_std_lib_path | def is_module_on_std_lib_path(cls, module):
"""
Sometimes .py files are symlinked to the real python files, such as the case of virtual
env. However the .pyc files are created under the virtual env directory rather than
the path in cls.STANDARD_LIB_PATH. Hence this function checks for both.
:param module: a module
:return: True if module is on interpreter's stdlib path. False otherwise.
"""
module_file_real_path = os.path.realpath(module.__file__)
if module_file_real_path.startswith(cls.STANDARD_LIB_PATH):
return True
elif os.path.splitext(module_file_real_path)[1] == '.pyc':
py_file_real_path = os.path.realpath(os.path.splitext(module_file_real_path)[0] + '.py')
return py_file_real_path.startswith(cls.STANDARD_LIB_PATH)
return False | python | def is_module_on_std_lib_path(cls, module):
module_file_real_path = os.path.realpath(module.__file__)
if module_file_real_path.startswith(cls.STANDARD_LIB_PATH):
return True
elif os.path.splitext(module_file_real_path)[1] == '.pyc':
py_file_real_path = os.path.realpath(os.path.splitext(module_file_real_path)[0] + '.py')
return py_file_real_path.startswith(cls.STANDARD_LIB_PATH)
return False | [
"def",
"is_module_on_std_lib_path",
"(",
"cls",
",",
"module",
")",
":",
"module_file_real_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"module",
".",
"__file__",
")",
"if",
"module_file_real_path",
".",
"startswith",
"(",
"cls",
".",
"STANDARD_LIB_PATH"... | Sometimes .py files are symlinked to the real python files, such as the case of virtual
env. However the .pyc files are created under the virtual env directory rather than
the path in cls.STANDARD_LIB_PATH. Hence this function checks for both.
:param module: a module
:return: True if module is on interpreter's stdlib path. False otherwise. | [
"Sometimes",
".",
"py",
"files",
"are",
"symlinked",
"to",
"the",
"real",
"python",
"files",
"such",
"as",
"the",
"case",
"of",
"virtual",
"env",
".",
"However",
"the",
".",
"pyc",
"files",
"are",
"created",
"under",
"the",
"virtual",
"env",
"directory",
... | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/import_order.py#L91-L106 |
224,025 | pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/import_order.py | ImportOrder.iter_import_chunks | def iter_import_chunks(self):
"""Iterate over space-separated import chunks in a file."""
chunk = []
last_line = None
for leaf in self.python_file.tree.body:
if isinstance(leaf, (ast.Import, ast.ImportFrom)):
# we've seen previous imports but this import is not in the same chunk
if last_line and leaf.lineno != last_line[1]:
yield chunk
chunk = [leaf]
# we've either not seen previous imports or this is part of the same chunk
elif not last_line or last_line and leaf.lineno == last_line[1]:
chunk.append(leaf)
last_line = self.python_file.logical_lines[leaf.lineno]
if chunk:
yield chunk | python | def iter_import_chunks(self):
chunk = []
last_line = None
for leaf in self.python_file.tree.body:
if isinstance(leaf, (ast.Import, ast.ImportFrom)):
# we've seen previous imports but this import is not in the same chunk
if last_line and leaf.lineno != last_line[1]:
yield chunk
chunk = [leaf]
# we've either not seen previous imports or this is part of the same chunk
elif not last_line or last_line and leaf.lineno == last_line[1]:
chunk.append(leaf)
last_line = self.python_file.logical_lines[leaf.lineno]
if chunk:
yield chunk | [
"def",
"iter_import_chunks",
"(",
"self",
")",
":",
"chunk",
"=",
"[",
"]",
"last_line",
"=",
"None",
"for",
"leaf",
"in",
"self",
".",
"python_file",
".",
"tree",
".",
"body",
":",
"if",
"isinstance",
"(",
"leaf",
",",
"(",
"ast",
".",
"Import",
","... | Iterate over space-separated import chunks in a file. | [
"Iterate",
"over",
"space",
"-",
"separated",
"import",
"chunks",
"in",
"a",
"file",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/import_order.py#L176-L191 |
224,026 | pantsbuild/pants | src/python/pants/backend/codegen/thrift/java/thrift_defaults.py | ThriftDefaults.compiler | def compiler(self, target):
"""Returns the thrift compiler to use for the given target.
:param target: The target to extract the thrift compiler from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The thrift compiler to use.
:rtype: string
"""
self._check_target(target)
return target.compiler or self._default_compiler | python | def compiler(self, target):
self._check_target(target)
return target.compiler or self._default_compiler | [
"def",
"compiler",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_check_target",
"(",
"target",
")",
"return",
"target",
".",
"compiler",
"or",
"self",
".",
"_default_compiler"
] | Returns the thrift compiler to use for the given target.
:param target: The target to extract the thrift compiler from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The thrift compiler to use.
:rtype: string | [
"Returns",
"the",
"thrift",
"compiler",
"to",
"use",
"for",
"the",
"given",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L40-L49 |
224,027 | pantsbuild/pants | src/python/pants/backend/codegen/thrift/java/thrift_defaults.py | ThriftDefaults.language | def language(self, target):
"""Returns the target language to generate thrift stubs for.
:param target: The target to extract the target language from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The target language to generate stubs for.
:rtype: string
"""
self._check_target(target)
return target.language or self._default_language | python | def language(self, target):
self._check_target(target)
return target.language or self._default_language | [
"def",
"language",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_check_target",
"(",
"target",
")",
"return",
"target",
".",
"language",
"or",
"self",
".",
"_default_language"
] | Returns the target language to generate thrift stubs for.
:param target: The target to extract the target language from.
:type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary`
:returns: The target language to generate stubs for.
:rtype: string | [
"Returns",
"the",
"target",
"language",
"to",
"generate",
"thrift",
"stubs",
"for",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L51-L60 |
224,028 | pantsbuild/pants | src/python/pants/backend/codegen/thrift/java/thrift_defaults.py | ThriftDefaults.namespace_map | def namespace_map(self, target):
"""Returns the namespace_map used for Thrift generation.
:param target: The target to extract the namespace_map from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: The namespaces to remap (old to new).
:rtype: dictionary
"""
self._check_target(target)
return target.namespace_map or self._default_namespace_map | python | def namespace_map(self, target):
self._check_target(target)
return target.namespace_map or self._default_namespace_map | [
"def",
"namespace_map",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_check_target",
"(",
"target",
")",
"return",
"target",
".",
"namespace_map",
"or",
"self",
".",
"_default_namespace_map"
] | Returns the namespace_map used for Thrift generation.
:param target: The target to extract the namespace_map from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: The namespaces to remap (old to new).
:rtype: dictionary | [
"Returns",
"the",
"namespace_map",
"used",
"for",
"Thrift",
"generation",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L62-L71 |
224,029 | pantsbuild/pants | src/python/pants/backend/codegen/thrift/java/thrift_defaults.py | ThriftDefaults.compiler_args | def compiler_args(self, target):
"""Returns the compiler_args used for Thrift generation.
:param target: The target to extract the compiler args from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: Extra arguments for the thrift compiler
:rtype: list
"""
self._check_target(target)
return target.compiler_args or self._default_compiler_args | python | def compiler_args(self, target):
self._check_target(target)
return target.compiler_args or self._default_compiler_args | [
"def",
"compiler_args",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_check_target",
"(",
"target",
")",
"return",
"target",
".",
"compiler_args",
"or",
"self",
".",
"_default_compiler_args"
] | Returns the compiler_args used for Thrift generation.
:param target: The target to extract the compiler args from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: Extra arguments for the thrift compiler
:rtype: list | [
"Returns",
"the",
"compiler_args",
"used",
"for",
"Thrift",
"generation",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L73-L82 |
224,030 | pantsbuild/pants | src/python/pants/backend/codegen/thrift/java/thrift_defaults.py | ThriftDefaults.default_java_namespace | def default_java_namespace(self, target):
"""Returns the default_java_namespace used for Thrift generation.
:param target: The target to extract the default_java_namespace from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: The default Java namespace used when not specified in the IDL.
:rtype: string
"""
self._check_target(target)
return target.default_java_namespace or self._default_default_java_namespace | python | def default_java_namespace(self, target):
self._check_target(target)
return target.default_java_namespace or self._default_default_java_namespace | [
"def",
"default_java_namespace",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_check_target",
"(",
"target",
")",
"return",
"target",
".",
"default_java_namespace",
"or",
"self",
".",
"_default_default_java_namespace"
] | Returns the default_java_namespace used for Thrift generation.
:param target: The target to extract the default_java_namespace from.
:type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`
:returns: The default Java namespace used when not specified in the IDL.
:rtype: string | [
"Returns",
"the",
"default_java_namespace",
"used",
"for",
"Thrift",
"generation",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L84-L93 |
224,031 | pantsbuild/pants | src/python/pants/task/unpack_remote_sources_base.py | UnpackRemoteSourcesBase._calculate_unpack_filter | def _calculate_unpack_filter(cls, includes=None, excludes=None, spec=None):
"""Take regex patterns and return a filter function.
:param list includes: List of include patterns to pass to _file_filter.
:param list excludes: List of exclude patterns to pass to _file_filter.
"""
include_patterns = cls.compile_patterns(includes or [],
field_name='include_patterns',
spec=spec)
logger.debug('include_patterns: {}'
.format(list(p.pattern for p in include_patterns)))
exclude_patterns = cls.compile_patterns(excludes or [],
field_name='exclude_patterns',
spec=spec)
logger.debug('exclude_patterns: {}'
.format(list(p.pattern for p in exclude_patterns)))
return lambda f: cls._file_filter(f, include_patterns, exclude_patterns) | python | def _calculate_unpack_filter(cls, includes=None, excludes=None, spec=None):
include_patterns = cls.compile_patterns(includes or [],
field_name='include_patterns',
spec=spec)
logger.debug('include_patterns: {}'
.format(list(p.pattern for p in include_patterns)))
exclude_patterns = cls.compile_patterns(excludes or [],
field_name='exclude_patterns',
spec=spec)
logger.debug('exclude_patterns: {}'
.format(list(p.pattern for p in exclude_patterns)))
return lambda f: cls._file_filter(f, include_patterns, exclude_patterns) | [
"def",
"_calculate_unpack_filter",
"(",
"cls",
",",
"includes",
"=",
"None",
",",
"excludes",
"=",
"None",
",",
"spec",
"=",
"None",
")",
":",
"include_patterns",
"=",
"cls",
".",
"compile_patterns",
"(",
"includes",
"or",
"[",
"]",
",",
"field_name",
"=",... | Take regex patterns and return a filter function.
:param list includes: List of include patterns to pass to _file_filter.
:param list excludes: List of exclude patterns to pass to _file_filter. | [
"Take",
"regex",
"patterns",
"and",
"return",
"a",
"filter",
"function",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/task/unpack_remote_sources_base.py#L93-L109 |
224,032 | pantsbuild/pants | contrib/scrooge/src/python/pants/contrib/scrooge/tasks/scrooge_gen.py | ScroogeGen._resolve_deps | def _resolve_deps(self, depmap):
"""Given a map of gen-key=>target specs, resolves the target specs into references."""
deps = defaultdict(lambda: OrderedSet())
for category, depspecs in depmap.items():
dependencies = deps[category]
for depspec in depspecs:
dep_address = Address.parse(depspec)
try:
self.context.build_graph.maybe_inject_address_closure(dep_address)
dependencies.add(self.context.build_graph.get_target(dep_address))
except AddressLookupError as e:
raise AddressLookupError('{}\n referenced from {} scope'.format(e, self.options_scope))
return deps | python | def _resolve_deps(self, depmap):
deps = defaultdict(lambda: OrderedSet())
for category, depspecs in depmap.items():
dependencies = deps[category]
for depspec in depspecs:
dep_address = Address.parse(depspec)
try:
self.context.build_graph.maybe_inject_address_closure(dep_address)
dependencies.add(self.context.build_graph.get_target(dep_address))
except AddressLookupError as e:
raise AddressLookupError('{}\n referenced from {} scope'.format(e, self.options_scope))
return deps | [
"def",
"_resolve_deps",
"(",
"self",
",",
"depmap",
")",
":",
"deps",
"=",
"defaultdict",
"(",
"lambda",
":",
"OrderedSet",
"(",
")",
")",
"for",
"category",
",",
"depspecs",
"in",
"depmap",
".",
"items",
"(",
")",
":",
"dependencies",
"=",
"deps",
"["... | Given a map of gen-key=>target specs, resolves the target specs into references. | [
"Given",
"a",
"map",
"of",
"gen",
"-",
"key",
"=",
">",
"target",
"specs",
"resolves",
"the",
"target",
"specs",
"into",
"references",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/scrooge/src/python/pants/contrib/scrooge/tasks/scrooge_gen.py#L99-L111 |
224,033 | pantsbuild/pants | src/python/pants/init/target_roots_calculator.py | TargetRootsCalculator.parse_specs | def parse_specs(cls, target_specs, build_root=None, exclude_patterns=None, tags=None):
"""Parse string specs into unique `Spec` objects.
:param iterable target_specs: An iterable of string specs.
:param string build_root: The path to the build root.
:returns: A `Specs` object.
"""
build_root = build_root or get_buildroot()
spec_parser = CmdLineSpecParser(build_root)
dependencies = tuple(OrderedSet(spec_parser.parse_spec(spec_str) for spec_str in target_specs))
return Specs(
dependencies=dependencies,
exclude_patterns=exclude_patterns if exclude_patterns else tuple(),
tags=tags) | python | def parse_specs(cls, target_specs, build_root=None, exclude_patterns=None, tags=None):
build_root = build_root or get_buildroot()
spec_parser = CmdLineSpecParser(build_root)
dependencies = tuple(OrderedSet(spec_parser.parse_spec(spec_str) for spec_str in target_specs))
return Specs(
dependencies=dependencies,
exclude_patterns=exclude_patterns if exclude_patterns else tuple(),
tags=tags) | [
"def",
"parse_specs",
"(",
"cls",
",",
"target_specs",
",",
"build_root",
"=",
"None",
",",
"exclude_patterns",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"build_root",
"=",
"build_root",
"or",
"get_buildroot",
"(",
")",
"spec_parser",
"=",
"CmdLineSpe... | Parse string specs into unique `Spec` objects.
:param iterable target_specs: An iterable of string specs.
:param string build_root: The path to the build root.
:returns: A `Specs` object. | [
"Parse",
"string",
"specs",
"into",
"unique",
"Spec",
"objects",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/init/target_roots_calculator.py#L33-L47 |
224,034 | pantsbuild/pants | src/python/pants/backend/python/tasks/resolve_requirements_task_base.py | ResolveRequirementsTaskBase.resolve_requirements | def resolve_requirements(self, interpreter, req_libs):
"""Requirements resolution for PEX files.
:param interpreter: Resolve against this :class:`PythonInterpreter`.
:param req_libs: A list of :class:`PythonRequirementLibrary` targets to resolve.
:returns: a PEX containing target requirements and any specified python dist targets.
"""
with self.invalidated(req_libs) as invalidation_check:
# If there are no relevant targets, we still go through the motions of resolving
# an empty set of requirements, to prevent downstream tasks from having to check
# for this special case.
if invalidation_check.all_vts:
target_set_id = VersionedTargetSet.from_versioned_targets(
invalidation_check.all_vts).cache_key.hash
else:
target_set_id = 'no_targets'
# We need to ensure that we are resolving for only the current platform if we are
# including local python dist targets that have native extensions.
targets_by_platform = pex_build_util.targets_by_platform(self.context.targets(), self._python_setup)
if self._python_native_code_settings.check_build_for_current_platform_only(targets_by_platform):
platforms = ['current']
else:
platforms = list(sorted(targets_by_platform.keys()))
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), target_set_id))
# Note that we check for the existence of the directory, instead of for invalid_vts,
# to cover the empty case.
if not os.path.isdir(path):
with safe_concurrent_creation(path) as safe_path:
pex_builder = PexBuilderWrapper.Factory.create(
builder=PEXBuilder(path=safe_path, interpreter=interpreter, copy=True),
log=self.context.log)
pex_builder.add_requirement_libs_from(req_libs, platforms=platforms)
pex_builder.freeze()
return PEX(path, interpreter=interpreter) | python | def resolve_requirements(self, interpreter, req_libs):
with self.invalidated(req_libs) as invalidation_check:
# If there are no relevant targets, we still go through the motions of resolving
# an empty set of requirements, to prevent downstream tasks from having to check
# for this special case.
if invalidation_check.all_vts:
target_set_id = VersionedTargetSet.from_versioned_targets(
invalidation_check.all_vts).cache_key.hash
else:
target_set_id = 'no_targets'
# We need to ensure that we are resolving for only the current platform if we are
# including local python dist targets that have native extensions.
targets_by_platform = pex_build_util.targets_by_platform(self.context.targets(), self._python_setup)
if self._python_native_code_settings.check_build_for_current_platform_only(targets_by_platform):
platforms = ['current']
else:
platforms = list(sorted(targets_by_platform.keys()))
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), target_set_id))
# Note that we check for the existence of the directory, instead of for invalid_vts,
# to cover the empty case.
if not os.path.isdir(path):
with safe_concurrent_creation(path) as safe_path:
pex_builder = PexBuilderWrapper.Factory.create(
builder=PEXBuilder(path=safe_path, interpreter=interpreter, copy=True),
log=self.context.log)
pex_builder.add_requirement_libs_from(req_libs, platforms=platforms)
pex_builder.freeze()
return PEX(path, interpreter=interpreter) | [
"def",
"resolve_requirements",
"(",
"self",
",",
"interpreter",
",",
"req_libs",
")",
":",
"with",
"self",
".",
"invalidated",
"(",
"req_libs",
")",
"as",
"invalidation_check",
":",
"# If there are no relevant targets, we still go through the motions of resolving",
"# an em... | Requirements resolution for PEX files.
:param interpreter: Resolve against this :class:`PythonInterpreter`.
:param req_libs: A list of :class:`PythonRequirementLibrary` targets to resolve.
:returns: a PEX containing target requirements and any specified python dist targets. | [
"Requirements",
"resolution",
"for",
"PEX",
"files",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/resolve_requirements_task_base.py#L61-L96 |
224,035 | pantsbuild/pants | src/python/pants/backend/python/tasks/resolve_requirements_task_base.py | ResolveRequirementsTaskBase.resolve_requirement_strings | def resolve_requirement_strings(self, interpreter, requirement_strings):
"""Resolve a list of pip-style requirement strings."""
requirement_strings = sorted(requirement_strings)
if len(requirement_strings) == 0:
req_strings_id = 'no_requirements'
elif len(requirement_strings) == 1:
req_strings_id = requirement_strings[0]
else:
req_strings_id = hash_all(requirement_strings)
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), req_strings_id))
if not os.path.isdir(path):
reqs = [PythonRequirement(req_str) for req_str in requirement_strings]
with safe_concurrent_creation(path) as safe_path:
pex_builder = PexBuilderWrapper.Factory.create(
builder=PEXBuilder(path=safe_path, interpreter=interpreter, copy=True),
log=self.context.log)
pex_builder.add_resolved_requirements(reqs)
pex_builder.freeze()
return PEX(path, interpreter=interpreter) | python | def resolve_requirement_strings(self, interpreter, requirement_strings):
requirement_strings = sorted(requirement_strings)
if len(requirement_strings) == 0:
req_strings_id = 'no_requirements'
elif len(requirement_strings) == 1:
req_strings_id = requirement_strings[0]
else:
req_strings_id = hash_all(requirement_strings)
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), req_strings_id))
if not os.path.isdir(path):
reqs = [PythonRequirement(req_str) for req_str in requirement_strings]
with safe_concurrent_creation(path) as safe_path:
pex_builder = PexBuilderWrapper.Factory.create(
builder=PEXBuilder(path=safe_path, interpreter=interpreter, copy=True),
log=self.context.log)
pex_builder.add_resolved_requirements(reqs)
pex_builder.freeze()
return PEX(path, interpreter=interpreter) | [
"def",
"resolve_requirement_strings",
"(",
"self",
",",
"interpreter",
",",
"requirement_strings",
")",
":",
"requirement_strings",
"=",
"sorted",
"(",
"requirement_strings",
")",
"if",
"len",
"(",
"requirement_strings",
")",
"==",
"0",
":",
"req_strings_id",
"=",
... | Resolve a list of pip-style requirement strings. | [
"Resolve",
"a",
"list",
"of",
"pip",
"-",
"style",
"requirement",
"strings",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/resolve_requirements_task_base.py#L98-L117 |
224,036 | pantsbuild/pants | src/python/pants/backend/python/tasks/resolve_requirements_task_base.py | ResolveRequirementsTaskBase.merged_pex | def merged_pex(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None):
"""Yields a pex builder at path with the given pexes already merged.
:rtype: :class:`pex.pex_builder.PEXBuilder`
"""
pex_paths = [pex.path() for pex in pexes if pex]
if pex_paths:
pex_info = pex_info.copy()
pex_info.merge_pex_path(':'.join(pex_paths))
with safe_concurrent_creation(path) as safe_path:
builder = PEXBuilder(safe_path, interpreter, pex_info=pex_info)
if interpeter_constraints:
for constraint in interpeter_constraints:
builder.add_interpreter_constraint(constraint)
yield builder | python | def merged_pex(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None):
pex_paths = [pex.path() for pex in pexes if pex]
if pex_paths:
pex_info = pex_info.copy()
pex_info.merge_pex_path(':'.join(pex_paths))
with safe_concurrent_creation(path) as safe_path:
builder = PEXBuilder(safe_path, interpreter, pex_info=pex_info)
if interpeter_constraints:
for constraint in interpeter_constraints:
builder.add_interpreter_constraint(constraint)
yield builder | [
"def",
"merged_pex",
"(",
"cls",
",",
"path",
",",
"pex_info",
",",
"interpreter",
",",
"pexes",
",",
"interpeter_constraints",
"=",
"None",
")",
":",
"pex_paths",
"=",
"[",
"pex",
".",
"path",
"(",
")",
"for",
"pex",
"in",
"pexes",
"if",
"pex",
"]",
... | Yields a pex builder at path with the given pexes already merged.
:rtype: :class:`pex.pex_builder.PEXBuilder` | [
"Yields",
"a",
"pex",
"builder",
"at",
"path",
"with",
"the",
"given",
"pexes",
"already",
"merged",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/resolve_requirements_task_base.py#L121-L136 |
224,037 | pantsbuild/pants | src/python/pants/backend/python/tasks/resolve_requirements_task_base.py | ResolveRequirementsTaskBase.merge_pexes | def merge_pexes(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None):
"""Generates a merged pex at path."""
with cls.merged_pex(path, pex_info, interpreter, pexes, interpeter_constraints) as builder:
builder.freeze() | python | def merge_pexes(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None):
with cls.merged_pex(path, pex_info, interpreter, pexes, interpeter_constraints) as builder:
builder.freeze() | [
"def",
"merge_pexes",
"(",
"cls",
",",
"path",
",",
"pex_info",
",",
"interpreter",
",",
"pexes",
",",
"interpeter_constraints",
"=",
"None",
")",
":",
"with",
"cls",
".",
"merged_pex",
"(",
"path",
",",
"pex_info",
",",
"interpreter",
",",
"pexes",
",",
... | Generates a merged pex at path. | [
"Generates",
"a",
"merged",
"pex",
"at",
"path",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/resolve_requirements_task_base.py#L139-L142 |
224,038 | pantsbuild/pants | src/python/pants/backend/python/subsystems/python_setup.py | PythonSetup.artifact_cache_dir | def artifact_cache_dir(self):
"""Note that this is unrelated to the general pants artifact cache."""
return (self.get_options().artifact_cache_dir or
os.path.join(self.scratch_dir, 'artifacts')) | python | def artifact_cache_dir(self):
return (self.get_options().artifact_cache_dir or
os.path.join(self.scratch_dir, 'artifacts')) | [
"def",
"artifact_cache_dir",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"get_options",
"(",
")",
".",
"artifact_cache_dir",
"or",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"scratch_dir",
",",
"'artifacts'",
")",
")"
] | Note that this is unrelated to the general pants artifact cache. | [
"Note",
"that",
"this",
"is",
"unrelated",
"to",
"the",
"general",
"pants",
"artifact",
"cache",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/python_setup.py#L116-L119 |
224,039 | pantsbuild/pants | src/python/pants/backend/python/subsystems/python_setup.py | PythonSetup.compatibility_or_constraints | def compatibility_or_constraints(self, target):
"""
Return either the compatibility of the given target, or the interpreter constraints.
If interpreter constraints are supplied by the CLI flag, return those only.
"""
if self.get_options().is_flagged('interpreter_constraints'):
return tuple(self.interpreter_constraints)
return tuple(target.compatibility or self.interpreter_constraints) | python | def compatibility_or_constraints(self, target):
if self.get_options().is_flagged('interpreter_constraints'):
return tuple(self.interpreter_constraints)
return tuple(target.compatibility or self.interpreter_constraints) | [
"def",
"compatibility_or_constraints",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"get_options",
"(",
")",
".",
"is_flagged",
"(",
"'interpreter_constraints'",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"interpreter_constraints",
")",
"return",... | Return either the compatibility of the given target, or the interpreter constraints.
If interpreter constraints are supplied by the CLI flag, return those only. | [
"Return",
"either",
"the",
"compatibility",
"of",
"the",
"given",
"target",
"or",
"the",
"interpreter",
"constraints",
".",
"If",
"interpreter",
"constraints",
"are",
"supplied",
"by",
"the",
"CLI",
"flag",
"return",
"those",
"only",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/python_setup.py#L125-L132 |
224,040 | pantsbuild/pants | src/python/pants/backend/python/subsystems/python_setup.py | PythonSetup.get_pex_python_paths | def get_pex_python_paths():
"""Returns a list of paths to Python interpreters as defined in a pexrc file.
These are provided by a PEX_PYTHON_PATH in either of '/etc/pexrc', '~/.pexrc'.
PEX_PYTHON_PATH defines a colon-separated list of paths to interpreters
that a pex can be built and run against.
"""
ppp = Variables.from_rc().get('PEX_PYTHON_PATH')
if ppp:
return ppp.split(os.pathsep)
else:
return [] | python | def get_pex_python_paths():
ppp = Variables.from_rc().get('PEX_PYTHON_PATH')
if ppp:
return ppp.split(os.pathsep)
else:
return [] | [
"def",
"get_pex_python_paths",
"(",
")",
":",
"ppp",
"=",
"Variables",
".",
"from_rc",
"(",
")",
".",
"get",
"(",
"'PEX_PYTHON_PATH'",
")",
"if",
"ppp",
":",
"return",
"ppp",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"else",
":",
"return",
"[",
"... | Returns a list of paths to Python interpreters as defined in a pexrc file.
These are provided by a PEX_PYTHON_PATH in either of '/etc/pexrc', '~/.pexrc'.
PEX_PYTHON_PATH defines a colon-separated list of paths to interpreters
that a pex can be built and run against. | [
"Returns",
"a",
"list",
"of",
"paths",
"to",
"Python",
"interpreters",
"as",
"defined",
"in",
"a",
"pexrc",
"file",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/python_setup.py#L167-L178 |
224,041 | pantsbuild/pants | src/python/pants/backend/python/subsystems/python_setup.py | PythonSetup.get_pyenv_paths | def get_pyenv_paths(pyenv_root_func=None):
"""Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
"""
pyenv_root_func = pyenv_root_func or get_pyenv_root
pyenv_root = pyenv_root_func()
if pyenv_root is None:
return []
versions_dir = os.path.join(pyenv_root, 'versions')
paths = []
for version in sorted(os.listdir(versions_dir)):
path = os.path.join(versions_dir, version, 'bin')
if os.path.isdir(path):
paths.append(path)
return paths | python | def get_pyenv_paths(pyenv_root_func=None):
pyenv_root_func = pyenv_root_func or get_pyenv_root
pyenv_root = pyenv_root_func()
if pyenv_root is None:
return []
versions_dir = os.path.join(pyenv_root, 'versions')
paths = []
for version in sorted(os.listdir(versions_dir)):
path = os.path.join(versions_dir, version, 'bin')
if os.path.isdir(path):
paths.append(path)
return paths | [
"def",
"get_pyenv_paths",
"(",
"pyenv_root_func",
"=",
"None",
")",
":",
"pyenv_root_func",
"=",
"pyenv_root_func",
"or",
"get_pyenv_root",
"pyenv_root",
"=",
"pyenv_root_func",
"(",
")",
"if",
"pyenv_root",
"is",
"None",
":",
"return",
"[",
"]",
"versions_dir",
... | Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing. | [
"Returns",
"a",
"list",
"of",
"paths",
"to",
"Python",
"interpreters",
"managed",
"by",
"pyenv",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/python_setup.py#L181-L197 |
224,042 | pantsbuild/pants | src/python/pants/auth/basic_auth.py | BasicAuth.authenticate | def authenticate(self, provider, creds=None, cookies=None):
"""Authenticate against the specified provider.
:param str provider: Authorize against this provider.
:param pants.auth.basic_auth.BasicAuthCreds creds: The creds to use.
If unspecified, assumes that creds are set in the netrc file.
:param pants.auth.cookies.Cookies cookies: Store the auth cookies in this instance.
If unspecified, uses the global instance.
:raises pants.auth.basic_auth.BasicAuthException: If auth fails due to misconfiguration or
rejection by the server.
"""
cookies = cookies or Cookies.global_instance()
if not provider:
raise BasicAuthException('No basic auth provider specified.')
provider_config = self.get_options().providers.get(provider)
if not provider_config:
raise BasicAuthException('No config found for provider {}.'.format(provider))
url = provider_config.get('url')
if not url:
raise BasicAuthException('No url found in config for provider {}.'.format(provider))
if not self.get_options().allow_insecure_urls and not url.startswith('https://'):
raise BasicAuthException('Auth url for provider {} is not secure: {}.'.format(provider, url))
if creds:
auth = requests.auth.HTTPBasicAuth(creds.username, creds.password)
else:
auth = None # requests will use the netrc creds.
response = requests.get(url, auth=auth)
if response.status_code != requests.codes.ok:
if response.status_code == requests.codes.unauthorized:
parsed = www_authenticate.parse(response.headers.get('WWW-Authenticate', ''))
if 'Basic' in parsed:
raise Challenged(url, response.status_code, response.reason, parsed['Basic']['realm'])
raise BasicAuthException(url, response.status_code, response.reason)
cookies.update(response.cookies) | python | def authenticate(self, provider, creds=None, cookies=None):
cookies = cookies or Cookies.global_instance()
if not provider:
raise BasicAuthException('No basic auth provider specified.')
provider_config = self.get_options().providers.get(provider)
if not provider_config:
raise BasicAuthException('No config found for provider {}.'.format(provider))
url = provider_config.get('url')
if not url:
raise BasicAuthException('No url found in config for provider {}.'.format(provider))
if not self.get_options().allow_insecure_urls and not url.startswith('https://'):
raise BasicAuthException('Auth url for provider {} is not secure: {}.'.format(provider, url))
if creds:
auth = requests.auth.HTTPBasicAuth(creds.username, creds.password)
else:
auth = None # requests will use the netrc creds.
response = requests.get(url, auth=auth)
if response.status_code != requests.codes.ok:
if response.status_code == requests.codes.unauthorized:
parsed = www_authenticate.parse(response.headers.get('WWW-Authenticate', ''))
if 'Basic' in parsed:
raise Challenged(url, response.status_code, response.reason, parsed['Basic']['realm'])
raise BasicAuthException(url, response.status_code, response.reason)
cookies.update(response.cookies) | [
"def",
"authenticate",
"(",
"self",
",",
"provider",
",",
"creds",
"=",
"None",
",",
"cookies",
"=",
"None",
")",
":",
"cookies",
"=",
"cookies",
"or",
"Cookies",
".",
"global_instance",
"(",
")",
"if",
"not",
"provider",
":",
"raise",
"BasicAuthException"... | Authenticate against the specified provider.
:param str provider: Authorize against this provider.
:param pants.auth.basic_auth.BasicAuthCreds creds: The creds to use.
If unspecified, assumes that creds are set in the netrc file.
:param pants.auth.cookies.Cookies cookies: Store the auth cookies in this instance.
If unspecified, uses the global instance.
:raises pants.auth.basic_auth.BasicAuthException: If auth fails due to misconfiguration or
rejection by the server. | [
"Authenticate",
"against",
"the",
"specified",
"provider",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/auth/basic_auth.py#L52-L91 |
224,043 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.glob1 | def glob1(self, dir_relpath, glob):
"""Returns a list of paths in path that match glob and are not ignored."""
if self.isignored(dir_relpath, directory=True):
return []
matched_files = self._glob1_raw(dir_relpath, glob)
prefix = self._relpath_no_dot(dir_relpath)
return self._filter_ignored(matched_files, selector=lambda p: os.path.join(prefix, p)) | python | def glob1(self, dir_relpath, glob):
if self.isignored(dir_relpath, directory=True):
return []
matched_files = self._glob1_raw(dir_relpath, glob)
prefix = self._relpath_no_dot(dir_relpath)
return self._filter_ignored(matched_files, selector=lambda p: os.path.join(prefix, p)) | [
"def",
"glob1",
"(",
"self",
",",
"dir_relpath",
",",
"glob",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"dir_relpath",
",",
"directory",
"=",
"True",
")",
":",
"return",
"[",
"]",
"matched_files",
"=",
"self",
".",
"_glob1_raw",
"(",
"dir_relpath",
... | Returns a list of paths in path that match glob and are not ignored. | [
"Returns",
"a",
"list",
"of",
"paths",
"in",
"path",
"that",
"match",
"glob",
"and",
"are",
"not",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L77-L84 |
224,044 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.scandir | def scandir(self, relpath):
"""Return paths relative to the root, which are in the given directory and not ignored."""
if self.isignored(relpath, directory=True):
self._raise_access_ignored(relpath)
return self._filter_ignored(self._scandir_raw(relpath), selector=lambda e: e.path) | python | def scandir(self, relpath):
if self.isignored(relpath, directory=True):
self._raise_access_ignored(relpath)
return self._filter_ignored(self._scandir_raw(relpath), selector=lambda e: e.path) | [
"def",
"scandir",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"relpath",
",",
"directory",
"=",
"True",
")",
":",
"self",
".",
"_raise_access_ignored",
"(",
"relpath",
")",
"return",
"self",
".",
"_filter_ignored",
"(",
"s... | Return paths relative to the root, which are in the given directory and not ignored. | [
"Return",
"paths",
"relative",
"to",
"the",
"root",
"which",
"are",
"in",
"the",
"given",
"directory",
"and",
"not",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L86-L91 |
224,045 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.isdir | def isdir(self, relpath):
"""Returns True if path is a directory and is not ignored."""
if self._isdir_raw(relpath):
if not self.isignored(relpath, directory=True):
return True
return False | python | def isdir(self, relpath):
if self._isdir_raw(relpath):
if not self.isignored(relpath, directory=True):
return True
return False | [
"def",
"isdir",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"_isdir_raw",
"(",
"relpath",
")",
":",
"if",
"not",
"self",
".",
"isignored",
"(",
"relpath",
",",
"directory",
"=",
"True",
")",
":",
"return",
"True",
"return",
"False"
] | Returns True if path is a directory and is not ignored. | [
"Returns",
"True",
"if",
"path",
"is",
"a",
"directory",
"and",
"is",
"not",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L93-L99 |
224,046 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.isfile | def isfile(self, relpath):
"""Returns True if path is a file and is not ignored."""
if self.isignored(relpath):
return False
return self._isfile_raw(relpath) | python | def isfile(self, relpath):
if self.isignored(relpath):
return False
return self._isfile_raw(relpath) | [
"def",
"isfile",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"relpath",
")",
":",
"return",
"False",
"return",
"self",
".",
"_isfile_raw",
"(",
"relpath",
")"
] | Returns True if path is a file and is not ignored. | [
"Returns",
"True",
"if",
"path",
"is",
"a",
"file",
"and",
"is",
"not",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L101-L105 |
224,047 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.exists | def exists(self, relpath):
"""Returns True if path exists and is not ignored."""
if self.isignored(self._append_slash_if_dir_path(relpath)):
return False
return self._exists_raw(relpath) | python | def exists(self, relpath):
if self.isignored(self._append_slash_if_dir_path(relpath)):
return False
return self._exists_raw(relpath) | [
"def",
"exists",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"self",
".",
"_append_slash_if_dir_path",
"(",
"relpath",
")",
")",
":",
"return",
"False",
"return",
"self",
".",
"_exists_raw",
"(",
"relpath",
")"
] | Returns True if path exists and is not ignored. | [
"Returns",
"True",
"if",
"path",
"exists",
"and",
"is",
"not",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L107-L111 |
224,048 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.content | def content(self, file_relpath):
"""Returns the content for file at path. Raises exception if path is ignored.
Raises exception if path is ignored.
"""
if self.isignored(file_relpath):
self._raise_access_ignored(file_relpath)
return self._content_raw(file_relpath) | python | def content(self, file_relpath):
if self.isignored(file_relpath):
self._raise_access_ignored(file_relpath)
return self._content_raw(file_relpath) | [
"def",
"content",
"(",
"self",
",",
"file_relpath",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"file_relpath",
")",
":",
"self",
".",
"_raise_access_ignored",
"(",
"file_relpath",
")",
"return",
"self",
".",
"_content_raw",
"(",
"file_relpath",
")"
] | Returns the content for file at path. Raises exception if path is ignored.
Raises exception if path is ignored. | [
"Returns",
"the",
"content",
"for",
"file",
"at",
"path",
".",
"Raises",
"exception",
"if",
"path",
"is",
"ignored",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L113-L121 |
224,049 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.relative_readlink | def relative_readlink(self, relpath):
"""Execute `readlink` for the given path, which may result in a relative path.
Raises exception if path is ignored.
"""
if self.isignored(self._append_slash_if_dir_path(relpath)):
self._raise_access_ignored(relpath)
return self._relative_readlink_raw(relpath) | python | def relative_readlink(self, relpath):
if self.isignored(self._append_slash_if_dir_path(relpath)):
self._raise_access_ignored(relpath)
return self._relative_readlink_raw(relpath) | [
"def",
"relative_readlink",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"isignored",
"(",
"self",
".",
"_append_slash_if_dir_path",
"(",
"relpath",
")",
")",
":",
"self",
".",
"_raise_access_ignored",
"(",
"relpath",
")",
"return",
"self",
".",... | Execute `readlink` for the given path, which may result in a relative path.
Raises exception if path is ignored. | [
"Execute",
"readlink",
"for",
"the",
"given",
"path",
"which",
"may",
"result",
"in",
"a",
"relative",
"path",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L123-L130 |
224,050 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.walk | def walk(self, relpath, topdown=True):
"""Walk the file tree rooted at `path`.
Works like os.walk but returned root value is relative path.
Ignored paths will not be returned.
"""
for root, dirs, files in self._walk_raw(relpath, topdown):
matched_dirs = self.ignore.match_files([os.path.join(root, "{}/".format(d)) for d in dirs])
matched_files = self.ignore.match_files([os.path.join(root, f) for f in files])
for matched_dir in matched_dirs:
dirs.remove(fast_relpath(matched_dir, root).rstrip('/'))
for matched_file in matched_files:
files.remove(fast_relpath(matched_file, root))
yield root, dirs, files | python | def walk(self, relpath, topdown=True):
for root, dirs, files in self._walk_raw(relpath, topdown):
matched_dirs = self.ignore.match_files([os.path.join(root, "{}/".format(d)) for d in dirs])
matched_files = self.ignore.match_files([os.path.join(root, f) for f in files])
for matched_dir in matched_dirs:
dirs.remove(fast_relpath(matched_dir, root).rstrip('/'))
for matched_file in matched_files:
files.remove(fast_relpath(matched_file, root))
yield root, dirs, files | [
"def",
"walk",
"(",
"self",
",",
"relpath",
",",
"topdown",
"=",
"True",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"self",
".",
"_walk_raw",
"(",
"relpath",
",",
"topdown",
")",
":",
"matched_dirs",
"=",
"self",
".",
"ignore",
".",
... | Walk the file tree rooted at `path`.
Works like os.walk but returned root value is relative path.
Ignored paths will not be returned. | [
"Walk",
"the",
"file",
"tree",
"rooted",
"at",
"path",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L132-L147 |
224,051 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree.isignored | def isignored(self, relpath, directory=False):
"""Returns True if path matches pants ignore pattern."""
relpath = self._relpath_no_dot(relpath)
if directory:
relpath = self._append_trailing_slash(relpath)
return self.ignore.match_file(relpath) | python | def isignored(self, relpath, directory=False):
relpath = self._relpath_no_dot(relpath)
if directory:
relpath = self._append_trailing_slash(relpath)
return self.ignore.match_file(relpath) | [
"def",
"isignored",
"(",
"self",
",",
"relpath",
",",
"directory",
"=",
"False",
")",
":",
"relpath",
"=",
"self",
".",
"_relpath_no_dot",
"(",
"relpath",
")",
"if",
"directory",
":",
"relpath",
"=",
"self",
".",
"_append_trailing_slash",
"(",
"relpath",
"... | Returns True if path matches pants ignore pattern. | [
"Returns",
"True",
"if",
"path",
"matches",
"pants",
"ignore",
"pattern",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L161-L166 |
224,052 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree._filter_ignored | def _filter_ignored(self, entries, selector=None):
"""Given an opaque entry list, filter any ignored entries.
:param entries: A list or generator that produces entries to filter.
:param selector: A function that computes a path for an entry relative to the root of the
ProjectTree, or None to use identity.
"""
selector = selector or (lambda x: x)
prefixed_entries = [(self._append_slash_if_dir_path(selector(entry)), entry)
for entry in entries]
ignored_paths = set(self.ignore.match_files(path for path, _ in prefixed_entries))
return [entry for path, entry in prefixed_entries if path not in ignored_paths] | python | def _filter_ignored(self, entries, selector=None):
selector = selector or (lambda x: x)
prefixed_entries = [(self._append_slash_if_dir_path(selector(entry)), entry)
for entry in entries]
ignored_paths = set(self.ignore.match_files(path for path, _ in prefixed_entries))
return [entry for path, entry in prefixed_entries if path not in ignored_paths] | [
"def",
"_filter_ignored",
"(",
"self",
",",
"entries",
",",
"selector",
"=",
"None",
")",
":",
"selector",
"=",
"selector",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
"prefixed_entries",
"=",
"[",
"(",
"self",
".",
"_append_slash_if_dir_path",
"(",
"selector... | Given an opaque entry list, filter any ignored entries.
:param entries: A list or generator that produces entries to filter.
:param selector: A function that computes a path for an entry relative to the root of the
ProjectTree, or None to use identity. | [
"Given",
"an",
"opaque",
"entry",
"list",
"filter",
"any",
"ignored",
"entries",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L168-L179 |
224,053 | pantsbuild/pants | src/python/pants/base/project_tree.py | ProjectTree._append_slash_if_dir_path | def _append_slash_if_dir_path(self, relpath):
"""For a dir path return a path that has a trailing slash."""
if self._isdir_raw(relpath):
return self._append_trailing_slash(relpath)
return relpath | python | def _append_slash_if_dir_path(self, relpath):
if self._isdir_raw(relpath):
return self._append_trailing_slash(relpath)
return relpath | [
"def",
"_append_slash_if_dir_path",
"(",
"self",
",",
"relpath",
")",
":",
"if",
"self",
".",
"_isdir_raw",
"(",
"relpath",
")",
":",
"return",
"self",
".",
"_append_trailing_slash",
"(",
"relpath",
")",
"return",
"relpath"
] | For a dir path return a path that has a trailing slash. | [
"For",
"a",
"dir",
"path",
"return",
"a",
"path",
"that",
"has",
"a",
"trailing",
"slash",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/project_tree.py#L192-L197 |
224,054 | pantsbuild/pants | src/python/pants/build_graph/import_remote_sources_mixin.py | ImportRemoteSourcesMixin.compute_dependency_specs | def compute_dependency_specs(cls, kwargs=None, payload=None):
"""Tack imported_target_specs onto the traversable_specs generator for this target."""
for spec in super(ImportRemoteSourcesMixin, cls).compute_dependency_specs(kwargs, payload):
yield spec
imported_target_specs = cls.imported_target_specs(kwargs=kwargs, payload=payload)
for spec in imported_target_specs:
yield spec | python | def compute_dependency_specs(cls, kwargs=None, payload=None):
for spec in super(ImportRemoteSourcesMixin, cls).compute_dependency_specs(kwargs, payload):
yield spec
imported_target_specs = cls.imported_target_specs(kwargs=kwargs, payload=payload)
for spec in imported_target_specs:
yield spec | [
"def",
"compute_dependency_specs",
"(",
"cls",
",",
"kwargs",
"=",
"None",
",",
"payload",
"=",
"None",
")",
":",
"for",
"spec",
"in",
"super",
"(",
"ImportRemoteSourcesMixin",
",",
"cls",
")",
".",
"compute_dependency_specs",
"(",
"kwargs",
",",
"payload",
... | Tack imported_target_specs onto the traversable_specs generator for this target. | [
"Tack",
"imported_target_specs",
"onto",
"the",
"traversable_specs",
"generator",
"for",
"this",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/import_remote_sources_mixin.py#L110-L117 |
224,055 | pantsbuild/pants | src/python/pants/cache/local_artifact_cache.py | BaseLocalArtifactCache._tmpfile | def _tmpfile(self, cache_key, use):
"""Allocate tempfile on same device as cache with a suffix chosen to prevent collisions"""
with temporary_file(suffix=cache_key.id + use, root_dir=self._cache_root,
permissions=self._permissions) as tmpfile:
yield tmpfile | python | def _tmpfile(self, cache_key, use):
with temporary_file(suffix=cache_key.id + use, root_dir=self._cache_root,
permissions=self._permissions) as tmpfile:
yield tmpfile | [
"def",
"_tmpfile",
"(",
"self",
",",
"cache_key",
",",
"use",
")",
":",
"with",
"temporary_file",
"(",
"suffix",
"=",
"cache_key",
".",
"id",
"+",
"use",
",",
"root_dir",
"=",
"self",
".",
"_cache_root",
",",
"permissions",
"=",
"self",
".",
"_permission... | Allocate tempfile on same device as cache with a suffix chosen to prevent collisions | [
"Allocate",
"tempfile",
"on",
"same",
"device",
"as",
"cache",
"with",
"a",
"suffix",
"chosen",
"to",
"prevent",
"collisions"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/local_artifact_cache.py#L41-L45 |
224,056 | pantsbuild/pants | src/python/pants/cache/local_artifact_cache.py | BaseLocalArtifactCache.insert_paths | def insert_paths(self, cache_key, paths):
"""Gather paths into artifact, store it, and yield the path to stored artifact tarball."""
with self._tmpfile(cache_key, 'write') as tmp:
self._artifact(tmp.name).collect(paths)
yield self._store_tarball(cache_key, tmp.name) | python | def insert_paths(self, cache_key, paths):
with self._tmpfile(cache_key, 'write') as tmp:
self._artifact(tmp.name).collect(paths)
yield self._store_tarball(cache_key, tmp.name) | [
"def",
"insert_paths",
"(",
"self",
",",
"cache_key",
",",
"paths",
")",
":",
"with",
"self",
".",
"_tmpfile",
"(",
"cache_key",
",",
"'write'",
")",
"as",
"tmp",
":",
"self",
".",
"_artifact",
"(",
"tmp",
".",
"name",
")",
".",
"collect",
"(",
"path... | Gather paths into artifact, store it, and yield the path to stored artifact tarball. | [
"Gather",
"paths",
"into",
"artifact",
"store",
"it",
"and",
"yield",
"the",
"path",
"to",
"stored",
"artifact",
"tarball",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/local_artifact_cache.py#L48-L52 |
224,057 | pantsbuild/pants | src/python/pants/cache/local_artifact_cache.py | BaseLocalArtifactCache.store_and_use_artifact | def store_and_use_artifact(self, cache_key, src, results_dir=None):
"""Store and then extract the artifact from the given `src` iterator for the given cache_key.
:param cache_key: Cache key for the artifact.
:param src: Iterator over binary data to store for the artifact.
:param str results_dir: The path to the expected destination of the artifact extraction: will
be cleared both before extraction, and after a failure to extract.
"""
with self._tmpfile(cache_key, 'read') as tmp:
for chunk in src:
tmp.write(chunk)
tmp.close()
tarball = self._store_tarball(cache_key, tmp.name)
artifact = self._artifact(tarball)
# NOTE(mateo): The two clean=True args passed in this method are likely safe, since the cache will by
# definition be dealing with unique results_dir, as opposed to the stable vt.results_dir (aka 'current').
# But if by chance it's passed the stable results_dir, safe_makedir(clean=True) will silently convert it
# from a symlink to a real dir and cause mysterious 'Operation not permitted' errors until the workdir is cleaned.
if results_dir is not None:
safe_mkdir(results_dir, clean=True)
try:
artifact.extract()
except Exception:
# Do our best to clean up after a failed artifact extraction. If a results_dir has been
# specified, it is "expected" to represent the output destination of the extracted
# artifact, and so removing it should clear any partially extracted state.
if results_dir is not None:
safe_mkdir(results_dir, clean=True)
safe_delete(tarball)
raise
return True | python | def store_and_use_artifact(self, cache_key, src, results_dir=None):
with self._tmpfile(cache_key, 'read') as tmp:
for chunk in src:
tmp.write(chunk)
tmp.close()
tarball = self._store_tarball(cache_key, tmp.name)
artifact = self._artifact(tarball)
# NOTE(mateo): The two clean=True args passed in this method are likely safe, since the cache will by
# definition be dealing with unique results_dir, as opposed to the stable vt.results_dir (aka 'current').
# But if by chance it's passed the stable results_dir, safe_makedir(clean=True) will silently convert it
# from a symlink to a real dir and cause mysterious 'Operation not permitted' errors until the workdir is cleaned.
if results_dir is not None:
safe_mkdir(results_dir, clean=True)
try:
artifact.extract()
except Exception:
# Do our best to clean up after a failed artifact extraction. If a results_dir has been
# specified, it is "expected" to represent the output destination of the extracted
# artifact, and so removing it should clear any partially extracted state.
if results_dir is not None:
safe_mkdir(results_dir, clean=True)
safe_delete(tarball)
raise
return True | [
"def",
"store_and_use_artifact",
"(",
"self",
",",
"cache_key",
",",
"src",
",",
"results_dir",
"=",
"None",
")",
":",
"with",
"self",
".",
"_tmpfile",
"(",
"cache_key",
",",
"'read'",
")",
"as",
"tmp",
":",
"for",
"chunk",
"in",
"src",
":",
"tmp",
"."... | Store and then extract the artifact from the given `src` iterator for the given cache_key.
:param cache_key: Cache key for the artifact.
:param src: Iterator over binary data to store for the artifact.
:param str results_dir: The path to the expected destination of the artifact extraction: will
be cleared both before extraction, and after a failure to extract. | [
"Store",
"and",
"then",
"extract",
"the",
"artifact",
"from",
"the",
"given",
"src",
"iterator",
"for",
"the",
"given",
"cache_key",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/local_artifact_cache.py#L54-L87 |
224,058 | pantsbuild/pants | src/python/pants/cache/local_artifact_cache.py | LocalArtifactCache.prune | def prune(self, root):
"""Prune stale cache files
If the option --cache-target-max-entry is greater than zero, then prune will remove all but n
old cache files for each target/task.
:param str root: The path under which cacheable artifacts will be cleaned
"""
max_entries_per_target = self._max_entries_per_target
if os.path.isdir(root) and max_entries_per_target:
safe_rm_oldest_items_in_dir(root, max_entries_per_target) | python | def prune(self, root):
max_entries_per_target = self._max_entries_per_target
if os.path.isdir(root) and max_entries_per_target:
safe_rm_oldest_items_in_dir(root, max_entries_per_target) | [
"def",
"prune",
"(",
"self",
",",
"root",
")",
":",
"max_entries_per_target",
"=",
"self",
".",
"_max_entries_per_target",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
"and",
"max_entries_per_target",
":",
"safe_rm_oldest_items_in_dir",
"(",
"root",
... | Prune stale cache files
If the option --cache-target-max-entry is greater than zero, then prune will remove all but n
old cache files for each target/task.
:param str root: The path under which cacheable artifacts will be cleaned | [
"Prune",
"stale",
"cache",
"files"
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/local_artifact_cache.py#L117-L128 |
224,059 | pantsbuild/pants | src/python/pants/base/hash_utils.py | hash_all | def hash_all(strs, digest=None):
"""Returns a hash of the concatenation of all the strings in strs.
If a hashlib message digest is not supplied a new sha1 message digest is used.
"""
digest = digest or hashlib.sha1()
for s in strs:
s = ensure_binary(s)
digest.update(s)
return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8') | python | def hash_all(strs, digest=None):
digest = digest or hashlib.sha1()
for s in strs:
s = ensure_binary(s)
digest.update(s)
return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8') | [
"def",
"hash_all",
"(",
"strs",
",",
"digest",
"=",
"None",
")",
":",
"digest",
"=",
"digest",
"or",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"s",
"in",
"strs",
":",
"s",
"=",
"ensure_binary",
"(",
"s",
")",
"digest",
".",
"update",
"(",
"s",
")"... | Returns a hash of the concatenation of all the strings in strs.
If a hashlib message digest is not supplied a new sha1 message digest is used. | [
"Returns",
"a",
"hash",
"of",
"the",
"concatenation",
"of",
"all",
"the",
"strings",
"in",
"strs",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/hash_utils.py#L19-L28 |
224,060 | pantsbuild/pants | src/python/pants/base/hash_utils.py | hash_file | def hash_file(path, digest=None):
"""Hashes the contents of the file at the given path and returns the hash digest in hex form.
If a hashlib message digest is not supplied a new sha1 message digest is used.
"""
digest = digest or hashlib.sha1()
with open(path, 'rb') as fd:
s = fd.read(8192)
while s:
digest.update(s)
s = fd.read(8192)
return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8') | python | def hash_file(path, digest=None):
digest = digest or hashlib.sha1()
with open(path, 'rb') as fd:
s = fd.read(8192)
while s:
digest.update(s)
s = fd.read(8192)
return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8') | [
"def",
"hash_file",
"(",
"path",
",",
"digest",
"=",
"None",
")",
":",
"digest",
"=",
"digest",
"or",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fd",
":",
"s",
"=",
"fd",
".",
"read",
"(",
"8192",
")... | Hashes the contents of the file at the given path and returns the hash digest in hex form.
If a hashlib message digest is not supplied a new sha1 message digest is used. | [
"Hashes",
"the",
"contents",
"of",
"the",
"file",
"at",
"the",
"given",
"path",
"and",
"returns",
"the",
"hash",
"digest",
"in",
"hex",
"form",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/hash_utils.py#L31-L42 |
224,061 | pantsbuild/pants | src/python/pants/base/hash_utils.py | json_hash | def json_hash(obj, digest=None, encoder=None):
"""Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json encoder.
:type encoder: :class:`json.JSONEncoder`
:returns: A hash of the given `obj` according to the given `encoder`.
:rtype: str
:API: public
"""
json_str = json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True, cls=encoder)
return hash_all(json_str, digest=digest) | python | def json_hash(obj, digest=None, encoder=None):
json_str = json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True, cls=encoder)
return hash_all(json_str, digest=digest) | [
"def",
"json_hash",
"(",
"obj",
",",
"digest",
"=",
"None",
",",
"encoder",
"=",
"None",
")",
":",
"json_str",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"ensure_ascii",
"=",
"True",
",",
"allow_nan",
"=",
"False",
",",
"sort_keys",
"=",
"True",
","... | Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json encoder.
:type encoder: :class:`json.JSONEncoder`
:returns: A hash of the given `obj` according to the given `encoder`.
:rtype: str
:API: public | [
"Hashes",
"obj",
"by",
"dumping",
"to",
"JSON",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/hash_utils.py#L107-L120 |
224,062 | pantsbuild/pants | src/python/pants/base/hash_utils.py | Sharder.is_in_shard | def is_in_shard(self, s):
"""Returns True iff the string s is in this shard.
:param string s: The string to check.
"""
return self.compute_shard(s, self._nshards) == self._shard | python | def is_in_shard(self, s):
return self.compute_shard(s, self._nshards) == self._shard | [
"def",
"is_in_shard",
"(",
"self",
",",
"s",
")",
":",
"return",
"self",
".",
"compute_shard",
"(",
"s",
",",
"self",
".",
"_nshards",
")",
"==",
"self",
".",
"_shard"
] | Returns True iff the string s is in this shard.
:param string s: The string to check. | [
"Returns",
"True",
"iff",
"the",
"string",
"s",
"is",
"in",
"this",
"shard",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/hash_utils.py#L178-L183 |
224,063 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/classpath_util.py | ClasspathUtil.classpath | def classpath(cls, targets, classpath_products, confs=('default',)):
"""Return the classpath as a list of paths covering all the passed targets.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The classpath as a list of path elements.
:rtype: list of string
"""
classpath_iter = cls._classpath_iter(classpath_products.get_for_targets(targets), confs=confs)
return list(classpath_iter) | python | def classpath(cls, targets, classpath_products, confs=('default',)):
classpath_iter = cls._classpath_iter(classpath_products.get_for_targets(targets), confs=confs)
return list(classpath_iter) | [
"def",
"classpath",
"(",
"cls",
",",
"targets",
",",
"classpath_products",
",",
"confs",
"=",
"(",
"'default'",
",",
")",
")",
":",
"classpath_iter",
"=",
"cls",
".",
"_classpath_iter",
"(",
"classpath_products",
".",
"get_for_targets",
"(",
"targets",
")",
... | Return the classpath as a list of paths covering all the passed targets.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The classpath as a list of path elements.
:rtype: list of string | [
"Return",
"the",
"classpath",
"as",
"a",
"list",
"of",
"paths",
"covering",
"all",
"the",
"passed",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/classpath_util.py#L68-L78 |
224,064 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/classpath_util.py | ClasspathUtil.internal_classpath | def internal_classpath(cls, targets, classpath_products, confs=('default',)):
"""Return the list of internal classpath entries for a classpath covering all `targets`.
Any classpath entries contributed by external dependencies will be omitted.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The classpath as a list of path elements.
:rtype: list of string
"""
classpath_tuples = classpath_products.get_internal_classpath_entries_for_targets(targets)
filtered_tuples_iter = cls._filtered_classpath_by_confs_iter(classpath_tuples, confs)
return [entry.path for entry in cls._entries_iter(filtered_tuples_iter)] | python | def internal_classpath(cls, targets, classpath_products, confs=('default',)):
classpath_tuples = classpath_products.get_internal_classpath_entries_for_targets(targets)
filtered_tuples_iter = cls._filtered_classpath_by_confs_iter(classpath_tuples, confs)
return [entry.path for entry in cls._entries_iter(filtered_tuples_iter)] | [
"def",
"internal_classpath",
"(",
"cls",
",",
"targets",
",",
"classpath_products",
",",
"confs",
"=",
"(",
"'default'",
",",
")",
")",
":",
"classpath_tuples",
"=",
"classpath_products",
".",
"get_internal_classpath_entries_for_targets",
"(",
"targets",
")",
"filte... | Return the list of internal classpath entries for a classpath covering all `targets`.
Any classpath entries contributed by external dependencies will be omitted.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The classpath as a list of path elements.
:rtype: list of string | [
"Return",
"the",
"list",
"of",
"internal",
"classpath",
"entries",
"for",
"a",
"classpath",
"covering",
"all",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/classpath_util.py#L89-L102 |
224,065 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/classpath_util.py | ClasspathUtil.classpath_by_targets | def classpath_by_targets(cls, targets, classpath_products, confs=('default',)):
"""Return classpath entries grouped by their targets for the given `targets`.
:param targets: The targets to lookup classpath products for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The ordered (target, classpath) mappings.
:rtype: OrderedDict
"""
classpath_target_tuples = classpath_products.get_product_target_mappings_for_targets(targets)
filtered_items_iter = filter(cls._accept_conf_filter(confs, lambda x: x[0][0]),
classpath_target_tuples)
# group (classpath_entry, target) tuples by targets
target_to_classpath = OrderedDict()
for classpath_entry, target in filtered_items_iter:
_, entry = classpath_entry
if not target in target_to_classpath:
target_to_classpath[target] = []
target_to_classpath[target].append(entry)
return target_to_classpath | python | def classpath_by_targets(cls, targets, classpath_products, confs=('default',)):
classpath_target_tuples = classpath_products.get_product_target_mappings_for_targets(targets)
filtered_items_iter = filter(cls._accept_conf_filter(confs, lambda x: x[0][0]),
classpath_target_tuples)
# group (classpath_entry, target) tuples by targets
target_to_classpath = OrderedDict()
for classpath_entry, target in filtered_items_iter:
_, entry = classpath_entry
if not target in target_to_classpath:
target_to_classpath[target] = []
target_to_classpath[target].append(entry)
return target_to_classpath | [
"def",
"classpath_by_targets",
"(",
"cls",
",",
"targets",
",",
"classpath_products",
",",
"confs",
"=",
"(",
"'default'",
",",
")",
")",
":",
"classpath_target_tuples",
"=",
"classpath_products",
".",
"get_product_target_mappings_for_targets",
"(",
"targets",
")",
... | Return classpath entries grouped by their targets for the given `targets`.
:param targets: The targets to lookup classpath products for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs: The list of confs for use by this classpath.
:returns: The ordered (target, classpath) mappings.
:rtype: OrderedDict | [
"Return",
"classpath",
"entries",
"grouped",
"by",
"their",
"targets",
"for",
"the",
"given",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/classpath_util.py#L105-L125 |
224,066 | pantsbuild/pants | src/python/pants/pantsd/service/pailgun_service.py | PailgunService._setup_pailgun | def _setup_pailgun(self):
"""Sets up a PailgunServer instance."""
# Constructs and returns a runnable PantsRunner.
def runner_factory(sock, arguments, environment):
return self._runner_class.create(
sock,
arguments,
environment,
self.services,
self._scheduler_service,
)
# Plumb the daemon's lifecycle lock to the `PailgunServer` to safeguard teardown.
# This indirection exists to allow the server to be created before PantsService.setup
# has been called to actually initialize the `services` field.
@contextmanager
def lifecycle_lock():
with self.services.lifecycle_lock:
yield
return PailgunServer(self._bind_addr, runner_factory, lifecycle_lock, self._request_complete_callback) | python | def _setup_pailgun(self):
# Constructs and returns a runnable PantsRunner.
def runner_factory(sock, arguments, environment):
return self._runner_class.create(
sock,
arguments,
environment,
self.services,
self._scheduler_service,
)
# Plumb the daemon's lifecycle lock to the `PailgunServer` to safeguard teardown.
# This indirection exists to allow the server to be created before PantsService.setup
# has been called to actually initialize the `services` field.
@contextmanager
def lifecycle_lock():
with self.services.lifecycle_lock:
yield
return PailgunServer(self._bind_addr, runner_factory, lifecycle_lock, self._request_complete_callback) | [
"def",
"_setup_pailgun",
"(",
"self",
")",
":",
"# Constructs and returns a runnable PantsRunner.",
"def",
"runner_factory",
"(",
"sock",
",",
"arguments",
",",
"environment",
")",
":",
"return",
"self",
".",
"_runner_class",
".",
"create",
"(",
"sock",
",",
"argu... | Sets up a PailgunServer instance. | [
"Sets",
"up",
"a",
"PailgunServer",
"instance",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/service/pailgun_service.py#L51-L71 |
224,067 | pantsbuild/pants | src/python/pants/reporting/html_reporter.py | HtmlReporter._emit | def _emit(self, s):
"""Append content to the main report file."""
if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all.
self._report_file.write(s)
self._report_file.flush() | python | def _emit(self, s):
if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all.
self._report_file.write(s)
self._report_file.flush() | [
"def",
"_emit",
"(",
"self",
",",
"s",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_html_dir",
")",
":",
"# Make sure we're not immediately after a clean-all.",
"self",
".",
"_report_file",
".",
"write",
"(",
"s",
")",
"self",
".",... | Append content to the main report file. | [
"Append",
"content",
"to",
"the",
"main",
"report",
"file",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/html_reporter.py#L431-L435 |
224,068 | pantsbuild/pants | src/python/pants/reporting/html_reporter.py | HtmlReporter._overwrite | def _overwrite(self, filename, func, force=False):
"""Overwrite a file with the specified contents.
Write times are tracked, too-frequent overwrites are skipped, for performance reasons.
:param filename: The path under the html dir to write to.
:param func: A no-arg function that returns the contents to write.
:param force: Whether to force a write now, regardless of the last overwrite time.
"""
now = int(time.time() * 1000)
last_overwrite_time = self._last_overwrite_time.get(filename) or now
# Overwrite only once per second.
if (now - last_overwrite_time >= 1000) or force:
if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all.
with open(os.path.join(self._html_dir, filename), 'w') as f:
f.write(func())
self._last_overwrite_time[filename] = now | python | def _overwrite(self, filename, func, force=False):
now = int(time.time() * 1000)
last_overwrite_time = self._last_overwrite_time.get(filename) or now
# Overwrite only once per second.
if (now - last_overwrite_time >= 1000) or force:
if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all.
with open(os.path.join(self._html_dir, filename), 'w') as f:
f.write(func())
self._last_overwrite_time[filename] = now | [
"def",
"_overwrite",
"(",
"self",
",",
"filename",
",",
"func",
",",
"force",
"=",
"False",
")",
":",
"now",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"last_overwrite_time",
"=",
"self",
".",
"_last_overwrite_time",
".",
"get",
... | Overwrite a file with the specified contents.
Write times are tracked, too-frequent overwrites are skipped, for performance reasons.
:param filename: The path under the html dir to write to.
:param func: A no-arg function that returns the contents to write.
:param force: Whether to force a write now, regardless of the last overwrite time. | [
"Overwrite",
"a",
"file",
"with",
"the",
"specified",
"contents",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/html_reporter.py#L437-L453 |
224,069 | pantsbuild/pants | src/python/pants/reporting/html_reporter.py | HtmlReporter._htmlify_text | def _htmlify_text(self, s):
"""Make text HTML-friendly."""
colored = self._handle_ansi_color_codes(html.escape(s))
return linkify(self._buildroot, colored, self._linkify_memo).replace('\n', '</br>') | python | def _htmlify_text(self, s):
colored = self._handle_ansi_color_codes(html.escape(s))
return linkify(self._buildroot, colored, self._linkify_memo).replace('\n', '</br>') | [
"def",
"_htmlify_text",
"(",
"self",
",",
"s",
")",
":",
"colored",
"=",
"self",
".",
"_handle_ansi_color_codes",
"(",
"html",
".",
"escape",
"(",
"s",
")",
")",
"return",
"linkify",
"(",
"self",
".",
"_buildroot",
",",
"colored",
",",
"self",
".",
"_l... | Make text HTML-friendly. | [
"Make",
"text",
"HTML",
"-",
"friendly",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/html_reporter.py#L455-L458 |
224,070 | pantsbuild/pants | src/python/pants/reporting/html_reporter.py | HtmlReporter._handle_ansi_color_codes | def _handle_ansi_color_codes(self, s):
"""Replace ansi escape sequences with spans of appropriately named css classes."""
parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
ret = []
span_depth = 0
# Note that len(parts) is always odd: text, code, text, code, ..., text.
for i in range(0, len(parts), 2):
ret.append(parts[i])
if i + 1 < len(parts):
for code in parts[i + 1].split(';'):
if code == 0: # Reset.
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
else:
ret.append('<span class="ansi-{}">'.format(code))
span_depth += 1
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
return ''.join(ret) | python | def _handle_ansi_color_codes(self, s):
parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
ret = []
span_depth = 0
# Note that len(parts) is always odd: text, code, text, code, ..., text.
for i in range(0, len(parts), 2):
ret.append(parts[i])
if i + 1 < len(parts):
for code in parts[i + 1].split(';'):
if code == 0: # Reset.
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
else:
ret.append('<span class="ansi-{}">'.format(code))
span_depth += 1
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
return ''.join(ret) | [
"def",
"_handle_ansi_color_codes",
"(",
"self",
",",
"s",
")",
":",
"parts",
"=",
"HtmlReporter",
".",
"_ANSI_COLOR_CODE_RE",
".",
"split",
"(",
"s",
")",
"ret",
"=",
"[",
"]",
"span_depth",
"=",
"0",
"# Note that len(parts) is always odd: text, code, text, code, ..... | Replace ansi escape sequences with spans of appropriately named css classes. | [
"Replace",
"ansi",
"escape",
"sequences",
"with",
"spans",
"of",
"appropriately",
"named",
"css",
"classes",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/html_reporter.py#L462-L483 |
224,071 | pantsbuild/pants | src/python/pants/bin/local_pants_runner.py | LocalPantsRunner.create | def create(cls, exiter, args, env, target_roots=None, daemon_graph_session=None,
options_bootstrapper=None):
"""Creates a new LocalPantsRunner instance by parsing options.
:param Exiter exiter: The Exiter instance to use for this run.
:param list args: The arguments (e.g. sys.argv) for this run.
:param dict env: The environment (e.g. os.environ) for this run.
:param TargetRoots target_roots: The target roots for this run.
:param LegacyGraphSession daemon_graph_session: The graph helper for this session.
:param OptionsBootstrapper options_bootstrapper: The OptionsBootstrapper instance to reuse.
"""
build_root = get_buildroot()
options, build_config, options_bootstrapper = cls.parse_options(
args,
env,
setup_logging=True,
options_bootstrapper=options_bootstrapper,
)
global_options = options.for_global_scope()
# Option values are usually computed lazily on demand,
# but command line options are eagerly computed for validation.
for scope in options.scope_to_flags.keys():
options.for_scope(scope)
# Verify configs.
if global_options.verify_config:
options_bootstrapper.verify_configs_against_options(options)
# If we're running with the daemon, we'll be handed a session from the
# resident graph helper - otherwise initialize a new one here.
graph_session = cls._maybe_init_graph_session(
daemon_graph_session,
options_bootstrapper,
build_config,
options
)
target_roots = cls._maybe_init_target_roots(
target_roots,
graph_session,
options,
build_root
)
profile_path = env.get('PANTS_PROFILE')
return cls(
build_root,
exiter,
options,
options_bootstrapper,
build_config,
target_roots,
graph_session,
daemon_graph_session is not None,
profile_path
) | python | def create(cls, exiter, args, env, target_roots=None, daemon_graph_session=None,
options_bootstrapper=None):
build_root = get_buildroot()
options, build_config, options_bootstrapper = cls.parse_options(
args,
env,
setup_logging=True,
options_bootstrapper=options_bootstrapper,
)
global_options = options.for_global_scope()
# Option values are usually computed lazily on demand,
# but command line options are eagerly computed for validation.
for scope in options.scope_to_flags.keys():
options.for_scope(scope)
# Verify configs.
if global_options.verify_config:
options_bootstrapper.verify_configs_against_options(options)
# If we're running with the daemon, we'll be handed a session from the
# resident graph helper - otherwise initialize a new one here.
graph_session = cls._maybe_init_graph_session(
daemon_graph_session,
options_bootstrapper,
build_config,
options
)
target_roots = cls._maybe_init_target_roots(
target_roots,
graph_session,
options,
build_root
)
profile_path = env.get('PANTS_PROFILE')
return cls(
build_root,
exiter,
options,
options_bootstrapper,
build_config,
target_roots,
graph_session,
daemon_graph_session is not None,
profile_path
) | [
"def",
"create",
"(",
"cls",
",",
"exiter",
",",
"args",
",",
"env",
",",
"target_roots",
"=",
"None",
",",
"daemon_graph_session",
"=",
"None",
",",
"options_bootstrapper",
"=",
"None",
")",
":",
"build_root",
"=",
"get_buildroot",
"(",
")",
"options",
",... | Creates a new LocalPantsRunner instance by parsing options.
:param Exiter exiter: The Exiter instance to use for this run.
:param list args: The arguments (e.g. sys.argv) for this run.
:param dict env: The environment (e.g. os.environ) for this run.
:param TargetRoots target_roots: The target roots for this run.
:param LegacyGraphSession daemon_graph_session: The graph helper for this session.
:param OptionsBootstrapper options_bootstrapper: The OptionsBootstrapper instance to reuse. | [
"Creates",
"a",
"new",
"LocalPantsRunner",
"instance",
"by",
"parsing",
"options",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/bin/local_pants_runner.py#L127-L185 |
224,072 | pantsbuild/pants | src/python/pants/bin/local_pants_runner.py | LocalPantsRunner._maybe_handle_help | def _maybe_handle_help(self):
"""Handle requests for `help` information."""
if self._options.help_request:
help_printer = HelpPrinter(self._options)
result = help_printer.print_help()
self._exiter(result) | python | def _maybe_handle_help(self):
if self._options.help_request:
help_printer = HelpPrinter(self._options)
result = help_printer.print_help()
self._exiter(result) | [
"def",
"_maybe_handle_help",
"(",
"self",
")",
":",
"if",
"self",
".",
"_options",
".",
"help_request",
":",
"help_printer",
"=",
"HelpPrinter",
"(",
"self",
".",
"_options",
")",
"result",
"=",
"help_printer",
".",
"print_help",
"(",
")",
"self",
".",
"_e... | Handle requests for `help` information. | [
"Handle",
"requests",
"for",
"help",
"information",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/bin/local_pants_runner.py#L237-L242 |
224,073 | pantsbuild/pants | src/python/pants/bin/local_pants_runner.py | LocalPantsRunner._compute_final_exit_code | def _compute_final_exit_code(*codes):
"""Returns the exit code with higher abs value in case of negative values."""
max_code = None
for code in codes:
if max_code is None or abs(max_code) < abs(code):
max_code = code
return max_code | python | def _compute_final_exit_code(*codes):
max_code = None
for code in codes:
if max_code is None or abs(max_code) < abs(code):
max_code = code
return max_code | [
"def",
"_compute_final_exit_code",
"(",
"*",
"codes",
")",
":",
"max_code",
"=",
"None",
"for",
"code",
"in",
"codes",
":",
"if",
"max_code",
"is",
"None",
"or",
"abs",
"(",
"max_code",
")",
"<",
"abs",
"(",
"code",
")",
":",
"max_code",
"=",
"code",
... | Returns the exit code with higher abs value in case of negative values. | [
"Returns",
"the",
"exit",
"code",
"with",
"higher",
"abs",
"value",
"in",
"case",
"of",
"negative",
"values",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/bin/local_pants_runner.py#L280-L286 |
224,074 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_task.py | GoTask.import_oracle | def import_oracle(self):
"""Return an import oracle that can help look up and categorize imports.
:rtype: :class:`ImportOracle`
"""
return ImportOracle(go_dist=self.go_dist, workunit_factory=self.context.new_workunit) | python | def import_oracle(self):
return ImportOracle(go_dist=self.go_dist, workunit_factory=self.context.new_workunit) | [
"def",
"import_oracle",
"(",
"self",
")",
":",
"return",
"ImportOracle",
"(",
"go_dist",
"=",
"self",
".",
"go_dist",
",",
"workunit_factory",
"=",
"self",
".",
"context",
".",
"new_workunit",
")"
] | Return an import oracle that can help look up and categorize imports.
:rtype: :class:`ImportOracle` | [
"Return",
"an",
"import",
"oracle",
"that",
"can",
"help",
"look",
"up",
"and",
"categorize",
"imports",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_task.py#L61-L66 |
224,075 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_task.py | ImportOracle.go_stdlib | def go_stdlib(self):
"""Return the set of all Go standard library import paths.
:rtype: frozenset of string
"""
out = self._go_dist.create_go_cmd('list', args=['std']).check_output()
return frozenset(out.decode('utf-8').strip().split()) | python | def go_stdlib(self):
out = self._go_dist.create_go_cmd('list', args=['std']).check_output()
return frozenset(out.decode('utf-8').strip().split()) | [
"def",
"go_stdlib",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"_go_dist",
".",
"create_go_cmd",
"(",
"'list'",
",",
"args",
"=",
"[",
"'std'",
"]",
")",
".",
"check_output",
"(",
")",
"return",
"frozenset",
"(",
"out",
".",
"decode",
"(",
"'utf... | Return the set of all Go standard library import paths.
:rtype: frozenset of string | [
"Return",
"the",
"set",
"of",
"all",
"Go",
"standard",
"library",
"import",
"paths",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_task.py#L94-L100 |
224,076 | pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_task.py | ImportOracle.list_imports | def list_imports(self, pkg, gopath=None):
"""Return a listing of the dependencies of the given package.
:param string pkg: The package whose files to list all dependencies of.
:param string gopath: An optional $GOPATH which points to a Go workspace containing `pkg`.
:returns: The import listing for `pkg` that represents all its dependencies.
:rtype: :class:`ImportOracle.ImportListing`
:raises: :class:`ImportOracle.ListDepsError` if there was a problem listing the dependencies
of `pkg`.
"""
go_cmd = self._go_dist.create_go_cmd('list', args=['-json', pkg], gopath=gopath)
with self._workunit_factory('list {}'.format(pkg), cmd=str(go_cmd),
labels=[WorkUnitLabel.TOOL]) as workunit:
# TODO(John Sirois): It would be nice to be able to tee the stdout to the workunit to we have
# a capture of the json available for inspection in the server console.
process = go_cmd.spawn(stdout=subprocess.PIPE, stderr=workunit.output('stderr'))
out, _ = process.communicate()
returncode = process.returncode
workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE)
if returncode != 0:
raise self.ListDepsError('Problem listing imports for {}: {} failed with exit code {}'
.format(pkg, go_cmd, returncode))
data = json.loads(out.decode('utf-8'))
# XTestImports are for black box tests. These test files live inside the package dir but
# declare a different package and thus can only access the public members of the package's
# production code. This style of test necessarily means the test file will import the main
# package. For pants, this would lead to a cyclic self-dependency, so we omit the main
# package as implicitly included as its own dependency.
x_test_imports = [i for i in data.get('XTestImports', []) if i != pkg]
return self.ImportListing(pkg_name=data.get('Name'),
imports=data.get('Imports', []),
test_imports=data.get('TestImports', []),
x_test_imports=x_test_imports) | python | def list_imports(self, pkg, gopath=None):
go_cmd = self._go_dist.create_go_cmd('list', args=['-json', pkg], gopath=gopath)
with self._workunit_factory('list {}'.format(pkg), cmd=str(go_cmd),
labels=[WorkUnitLabel.TOOL]) as workunit:
# TODO(John Sirois): It would be nice to be able to tee the stdout to the workunit to we have
# a capture of the json available for inspection in the server console.
process = go_cmd.spawn(stdout=subprocess.PIPE, stderr=workunit.output('stderr'))
out, _ = process.communicate()
returncode = process.returncode
workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE)
if returncode != 0:
raise self.ListDepsError('Problem listing imports for {}: {} failed with exit code {}'
.format(pkg, go_cmd, returncode))
data = json.loads(out.decode('utf-8'))
# XTestImports are for black box tests. These test files live inside the package dir but
# declare a different package and thus can only access the public members of the package's
# production code. This style of test necessarily means the test file will import the main
# package. For pants, this would lead to a cyclic self-dependency, so we omit the main
# package as implicitly included as its own dependency.
x_test_imports = [i for i in data.get('XTestImports', []) if i != pkg]
return self.ImportListing(pkg_name=data.get('Name'),
imports=data.get('Imports', []),
test_imports=data.get('TestImports', []),
x_test_imports=x_test_imports) | [
"def",
"list_imports",
"(",
"self",
",",
"pkg",
",",
"gopath",
"=",
"None",
")",
":",
"go_cmd",
"=",
"self",
".",
"_go_dist",
".",
"create_go_cmd",
"(",
"'list'",
",",
"args",
"=",
"[",
"'-json'",
",",
"pkg",
"]",
",",
"gopath",
"=",
"gopath",
")",
... | Return a listing of the dependencies of the given package.
:param string pkg: The package whose files to list all dependencies of.
:param string gopath: An optional $GOPATH which points to a Go workspace containing `pkg`.
:returns: The import listing for `pkg` that represents all its dependencies.
:rtype: :class:`ImportOracle.ImportListing`
:raises: :class:`ImportOracle.ListDepsError` if there was a problem listing the dependencies
of `pkg`. | [
"Return",
"a",
"listing",
"of",
"the",
"dependencies",
"of",
"the",
"given",
"package",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_task.py#L139-L173 |
224,077 | pantsbuild/pants | src/python/pants/reporting/linkify.py | linkify | def linkify(buildroot, s, memoized_urls):
"""Augment text by heuristically finding URL and file references and turning them into links.
:param string buildroot: The base directory of the project.
:param string s: The text to insert links into.
:param dict memoized_urls: A cache of text to links so repeated substitutions don't require
additional file stats calls.
"""
def memoized_to_url(m):
# to_url uses None to signal not to replace the text,
# so we use a different sentinel value.
value = memoized_urls.get(m.group(0), _NO_URL)
if value is _NO_URL:
value = to_url(m)
memoized_urls[m.group(0)] = value
return value
def to_url(m):
if m.group(1):
return m.group(0) # It's an http(s) url.
path = m.group(0)
if path.startswith('/'):
path = os.path.relpath(path, buildroot)
elif path.startswith('..'):
# The path is not located inside the buildroot, so it's definitely not a BUILD file.
return None
else:
# The path is located in the buildroot: see if it's a reference to a target in a BUILD file.
parts = path.split(':')
if len(parts) == 2:
putative_dir = parts[0]
else:
putative_dir = path
if os.path.isdir(os.path.join(buildroot, putative_dir)):
build_files = list(BuildFile.get_build_files_family(
FileSystemProjectTree(buildroot),
putative_dir))
if build_files:
path = build_files[0].relpath
else:
return None
if os.path.exists(os.path.join(buildroot, path)):
# The reporting server serves file content at /browse/<path_from_buildroot>.
return '/browse/{}'.format(path)
else:
return None
def maybe_add_link(url, text):
return '<a target="_blank" href="{}">{}</a>'.format(url, text) if url else text
return _PATH_RE.sub(lambda m: maybe_add_link(memoized_to_url(m), m.group(0)), s) | python | def linkify(buildroot, s, memoized_urls):
def memoized_to_url(m):
# to_url uses None to signal not to replace the text,
# so we use a different sentinel value.
value = memoized_urls.get(m.group(0), _NO_URL)
if value is _NO_URL:
value = to_url(m)
memoized_urls[m.group(0)] = value
return value
def to_url(m):
if m.group(1):
return m.group(0) # It's an http(s) url.
path = m.group(0)
if path.startswith('/'):
path = os.path.relpath(path, buildroot)
elif path.startswith('..'):
# The path is not located inside the buildroot, so it's definitely not a BUILD file.
return None
else:
# The path is located in the buildroot: see if it's a reference to a target in a BUILD file.
parts = path.split(':')
if len(parts) == 2:
putative_dir = parts[0]
else:
putative_dir = path
if os.path.isdir(os.path.join(buildroot, putative_dir)):
build_files = list(BuildFile.get_build_files_family(
FileSystemProjectTree(buildroot),
putative_dir))
if build_files:
path = build_files[0].relpath
else:
return None
if os.path.exists(os.path.join(buildroot, path)):
# The reporting server serves file content at /browse/<path_from_buildroot>.
return '/browse/{}'.format(path)
else:
return None
def maybe_add_link(url, text):
return '<a target="_blank" href="{}">{}</a>'.format(url, text) if url else text
return _PATH_RE.sub(lambda m: maybe_add_link(memoized_to_url(m), m.group(0)), s) | [
"def",
"linkify",
"(",
"buildroot",
",",
"s",
",",
"memoized_urls",
")",
":",
"def",
"memoized_to_url",
"(",
"m",
")",
":",
"# to_url uses None to signal not to replace the text,",
"# so we use a different sentinel value.",
"value",
"=",
"memoized_urls",
".",
"get",
"("... | Augment text by heuristically finding URL and file references and turning them into links.
:param string buildroot: The base directory of the project.
:param string s: The text to insert links into.
:param dict memoized_urls: A cache of text to links so repeated substitutions don't require
additional file stats calls. | [
"Augment",
"text",
"by",
"heuristically",
"finding",
"URL",
"and",
"file",
"references",
"and",
"turning",
"them",
"into",
"links",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/linkify.py#L38-L90 |
224,078 | pantsbuild/pants | src/python/pants/base/validation.py | assert_list | def assert_list(obj, expected_type=string_types, can_be_none=True, default=(), key_arg=None,
allowable=(list, Fileset, OrderedSet, set, tuple), raise_type=ValueError):
"""
This function is used to ensure that parameters set by users in BUILD files are of acceptable types.
:API: public
:param obj : the object that may be a list. It will pass if it is of type in allowable.
:param expected_type : this is the expected type of the returned list contents.
:param can_be_none : this defines whether or not the obj can be None. If True, return default.
:param default : this is the default to return if can_be_none is True and obj is None.
:param key_arg : this is the name of the key to which obj belongs to
:param allowable : the acceptable types for obj. We do not want to allow any iterable (eg string).
:param raise_type : the error to throw if the type is not correct.
"""
def get_key_msg(key=None):
if key is None:
return ''
else:
return "In key '{}': ".format(key)
allowable = tuple(allowable)
key_msg = get_key_msg(key_arg)
val = obj
if val is None:
if can_be_none:
val = list(default)
else:
raise raise_type(
'{}Expected an object of acceptable type {}, received None and can_be_none is False'
.format(key_msg, allowable))
if isinstance(val, allowable):
lst = list(val)
for e in lst:
if not isinstance(e, expected_type):
raise raise_type(
'{}Expected a list containing values of type {}, instead got a value {} of {}'
.format(key_msg, expected_type, e, e.__class__))
return lst
else:
raise raise_type(
'{}Expected an object of acceptable type {}, received {} instead'
.format(key_msg, allowable, val)) | python | def assert_list(obj, expected_type=string_types, can_be_none=True, default=(), key_arg=None,
allowable=(list, Fileset, OrderedSet, set, tuple), raise_type=ValueError):
def get_key_msg(key=None):
if key is None:
return ''
else:
return "In key '{}': ".format(key)
allowable = tuple(allowable)
key_msg = get_key_msg(key_arg)
val = obj
if val is None:
if can_be_none:
val = list(default)
else:
raise raise_type(
'{}Expected an object of acceptable type {}, received None and can_be_none is False'
.format(key_msg, allowable))
if isinstance(val, allowable):
lst = list(val)
for e in lst:
if not isinstance(e, expected_type):
raise raise_type(
'{}Expected a list containing values of type {}, instead got a value {} of {}'
.format(key_msg, expected_type, e, e.__class__))
return lst
else:
raise raise_type(
'{}Expected an object of acceptable type {}, received {} instead'
.format(key_msg, allowable, val)) | [
"def",
"assert_list",
"(",
"obj",
",",
"expected_type",
"=",
"string_types",
",",
"can_be_none",
"=",
"True",
",",
"default",
"=",
"(",
")",
",",
"key_arg",
"=",
"None",
",",
"allowable",
"=",
"(",
"list",
",",
"Fileset",
",",
"OrderedSet",
",",
"set",
... | This function is used to ensure that parameters set by users in BUILD files are of acceptable types.
:API: public
:param obj : the object that may be a list. It will pass if it is of type in allowable.
:param expected_type : this is the expected type of the returned list contents.
:param can_be_none : this defines whether or not the obj can be None. If True, return default.
:param default : this is the default to return if can_be_none is True and obj is None.
:param key_arg : this is the name of the key to which obj belongs to
:param allowable : the acceptable types for obj. We do not want to allow any iterable (eg string).
:param raise_type : the error to throw if the type is not correct. | [
"This",
"function",
"is",
"used",
"to",
"ensure",
"that",
"parameters",
"set",
"by",
"users",
"in",
"BUILD",
"files",
"are",
"of",
"acceptable",
"types",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/validation.py#L12-L56 |
224,079 | pantsbuild/pants | src/python/pants/goal/aggregated_timings.py | AggregatedTimings.add_timing | def add_timing(self, label, secs, is_tool=False):
"""Aggregate timings by label.
secs - a double, so fractional seconds are allowed.
is_tool - whether this label represents a tool invocation.
"""
self._timings_by_path[label] += secs
if is_tool:
self._tool_labels.add(label)
# Check existence in case we're a clean-all. We don't want to write anything in that case.
if self._path and os.path.exists(os.path.dirname(self._path)):
with open(self._path, 'w') as f:
for x in self.get_all():
f.write('{label}: {timing}\n'.format(**x)) | python | def add_timing(self, label, secs, is_tool=False):
self._timings_by_path[label] += secs
if is_tool:
self._tool_labels.add(label)
# Check existence in case we're a clean-all. We don't want to write anything in that case.
if self._path and os.path.exists(os.path.dirname(self._path)):
with open(self._path, 'w') as f:
for x in self.get_all():
f.write('{label}: {timing}\n'.format(**x)) | [
"def",
"add_timing",
"(",
"self",
",",
"label",
",",
"secs",
",",
"is_tool",
"=",
"False",
")",
":",
"self",
".",
"_timings_by_path",
"[",
"label",
"]",
"+=",
"secs",
"if",
"is_tool",
":",
"self",
".",
"_tool_labels",
".",
"add",
"(",
"label",
")",
"... | Aggregate timings by label.
secs - a double, so fractional seconds are allowed.
is_tool - whether this label represents a tool invocation. | [
"Aggregate",
"timings",
"by",
"label",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/aggregated_timings.py#L28-L41 |
224,080 | pantsbuild/pants | src/python/pants/goal/aggregated_timings.py | AggregatedTimings.get_all | def get_all(self):
"""Returns all the timings, sorted in decreasing order.
Each value is a dict: { path: <path>, timing: <timing in seconds> }
"""
return [{'label': x[0], 'timing': x[1], 'is_tool': x[0] in self._tool_labels}
for x in sorted(self._timings_by_path.items(), key=lambda x: x[1], reverse=True)] | python | def get_all(self):
return [{'label': x[0], 'timing': x[1], 'is_tool': x[0] in self._tool_labels}
for x in sorted(self._timings_by_path.items(), key=lambda x: x[1], reverse=True)] | [
"def",
"get_all",
"(",
"self",
")",
":",
"return",
"[",
"{",
"'label'",
":",
"x",
"[",
"0",
"]",
",",
"'timing'",
":",
"x",
"[",
"1",
"]",
",",
"'is_tool'",
":",
"x",
"[",
"0",
"]",
"in",
"self",
".",
"_tool_labels",
"}",
"for",
"x",
"in",
"s... | Returns all the timings, sorted in decreasing order.
Each value is a dict: { path: <path>, timing: <timing in seconds> } | [
"Returns",
"all",
"the",
"timings",
"sorted",
"in",
"decreasing",
"order",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/aggregated_timings.py#L43-L49 |
224,081 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.files_for_target | def files_for_target(self, target):
"""Yields a sequence of abs path of source, class or jar files provided by the target.
The runtime classpath for a target must already have been finalized for a target in order
to compute its provided files.
"""
def gen():
# Compute src -> target.
if isinstance(target, JvmTarget):
for src in target.sources_relative_to_buildroot():
yield os.path.join(self.buildroot, src)
# TODO(Tejal Desai): pantsbuild/pants/65: Remove java_sources attribute for ScalaLibrary
if isinstance(target, ScalaLibrary):
for java_source in target.java_sources:
for src in java_source.sources_relative_to_buildroot():
yield os.path.join(self.buildroot, src)
# Compute classfile -> target and jar -> target.
files = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)
# And jars; for binary deps, zinc doesn't emit precise deps (yet).
cp_entries = ClasspathUtil.classpath((target,), self.runtime_classpath)
jars = [cpe for cpe in cp_entries if ClasspathUtil.is_jar(cpe)]
for coll in [files, jars]:
for f in coll:
yield f
return set(gen()) | python | def files_for_target(self, target):
def gen():
# Compute src -> target.
if isinstance(target, JvmTarget):
for src in target.sources_relative_to_buildroot():
yield os.path.join(self.buildroot, src)
# TODO(Tejal Desai): pantsbuild/pants/65: Remove java_sources attribute for ScalaLibrary
if isinstance(target, ScalaLibrary):
for java_source in target.java_sources:
for src in java_source.sources_relative_to_buildroot():
yield os.path.join(self.buildroot, src)
# Compute classfile -> target and jar -> target.
files = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)
# And jars; for binary deps, zinc doesn't emit precise deps (yet).
cp_entries = ClasspathUtil.classpath((target,), self.runtime_classpath)
jars = [cpe for cpe in cp_entries if ClasspathUtil.is_jar(cpe)]
for coll in [files, jars]:
for f in coll:
yield f
return set(gen()) | [
"def",
"files_for_target",
"(",
"self",
",",
"target",
")",
":",
"def",
"gen",
"(",
")",
":",
"# Compute src -> target.",
"if",
"isinstance",
"(",
"target",
",",
"JvmTarget",
")",
":",
"for",
"src",
"in",
"target",
".",
"sources_relative_to_buildroot",
"(",
... | Yields a sequence of abs path of source, class or jar files provided by the target.
The runtime classpath for a target must already have been finalized for a target in order
to compute its provided files. | [
"Yields",
"a",
"sequence",
"of",
"abs",
"path",
"of",
"source",
"class",
"or",
"jar",
"files",
"provided",
"by",
"the",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L35-L60 |
224,082 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.targets_by_file | def targets_by_file(self, targets):
"""Returns a map from abs path of source, class or jar file to an OrderedSet of targets.
The value is usually a singleton, because a source or class file belongs to a single target.
However a single jar may be provided (transitively or intransitively) by multiple JarLibrary
targets. But if there is a JarLibrary target that depends on a jar directly, then that
"canonical" target will be the first one in the list of targets.
"""
targets_by_file = defaultdict(OrderedSet)
for target in targets:
for f in self.files_for_target(target):
targets_by_file[f].add(target)
return targets_by_file | python | def targets_by_file(self, targets):
targets_by_file = defaultdict(OrderedSet)
for target in targets:
for f in self.files_for_target(target):
targets_by_file[f].add(target)
return targets_by_file | [
"def",
"targets_by_file",
"(",
"self",
",",
"targets",
")",
":",
"targets_by_file",
"=",
"defaultdict",
"(",
"OrderedSet",
")",
"for",
"target",
"in",
"targets",
":",
"for",
"f",
"in",
"self",
".",
"files_for_target",
"(",
"target",
")",
":",
"targets_by_fil... | Returns a map from abs path of source, class or jar file to an OrderedSet of targets.
The value is usually a singleton, because a source or class file belongs to a single target.
However a single jar may be provided (transitively or intransitively) by multiple JarLibrary
targets. But if there is a JarLibrary target that depends on a jar directly, then that
"canonical" target will be the first one in the list of targets. | [
"Returns",
"a",
"map",
"from",
"abs",
"path",
"of",
"source",
"class",
"or",
"jar",
"file",
"to",
"an",
"OrderedSet",
"of",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L62-L76 |
224,083 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.targets_for_class | def targets_for_class(self, target, classname):
"""Search which targets from `target`'s transitive dependencies contain `classname`."""
targets_with_class = set()
for target in target.closure():
for one_class in self._target_classes(target):
if classname in one_class:
targets_with_class.add(target)
break
return targets_with_class | python | def targets_for_class(self, target, classname):
targets_with_class = set()
for target in target.closure():
for one_class in self._target_classes(target):
if classname in one_class:
targets_with_class.add(target)
break
return targets_with_class | [
"def",
"targets_for_class",
"(",
"self",
",",
"target",
",",
"classname",
")",
":",
"targets_with_class",
"=",
"set",
"(",
")",
"for",
"target",
"in",
"target",
".",
"closure",
"(",
")",
":",
"for",
"one_class",
"in",
"self",
".",
"_target_classes",
"(",
... | Search which targets from `target`'s transitive dependencies contain `classname`. | [
"Search",
"which",
"targets",
"from",
"target",
"s",
"transitive",
"dependencies",
"contain",
"classname",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L78-L87 |
224,084 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer._target_classes | def _target_classes(self, target):
"""Set of target's provided classes.
Call at the target level is to memoize efficiently.
"""
target_classes = set()
contents = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)
for f in contents:
classname = ClasspathUtil.classname_for_rel_classfile(f)
if classname:
target_classes.add(classname)
return target_classes | python | def _target_classes(self, target):
target_classes = set()
contents = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)
for f in contents:
classname = ClasspathUtil.classname_for_rel_classfile(f)
if classname:
target_classes.add(classname)
return target_classes | [
"def",
"_target_classes",
"(",
"self",
",",
"target",
")",
":",
"target_classes",
"=",
"set",
"(",
")",
"contents",
"=",
"ClasspathUtil",
".",
"classpath_contents",
"(",
"(",
"target",
",",
")",
",",
"self",
".",
"runtime_classpath",
")",
"for",
"f",
"in",... | Set of target's provided classes.
Call at the target level is to memoize efficiently. | [
"Set",
"of",
"target",
"s",
"provided",
"classes",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L90-L101 |
224,085 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer._jar_classfiles | def _jar_classfiles(self, jar_file):
"""Returns an iterator over the classfiles inside jar_file."""
for cls in ClasspathUtil.classpath_entries_contents([jar_file]):
if cls.endswith('.class'):
yield cls | python | def _jar_classfiles(self, jar_file):
for cls in ClasspathUtil.classpath_entries_contents([jar_file]):
if cls.endswith('.class'):
yield cls | [
"def",
"_jar_classfiles",
"(",
"self",
",",
"jar_file",
")",
":",
"for",
"cls",
"in",
"ClasspathUtil",
".",
"classpath_entries_contents",
"(",
"[",
"jar_file",
"]",
")",
":",
"if",
"cls",
".",
"endswith",
"(",
"'.class'",
")",
":",
"yield",
"cls"
] | Returns an iterator over the classfiles inside jar_file. | [
"Returns",
"an",
"iterator",
"over",
"the",
"classfiles",
"inside",
"jar_file",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L103-L107 |
224,086 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.bootstrap_jar_classfiles | def bootstrap_jar_classfiles(self):
"""Returns a set of classfiles from the JVM bootstrap jars."""
bootstrap_jar_classfiles = set()
for jar_file in self._find_all_bootstrap_jars():
for cls in self._jar_classfiles(jar_file):
bootstrap_jar_classfiles.add(cls)
return bootstrap_jar_classfiles | python | def bootstrap_jar_classfiles(self):
bootstrap_jar_classfiles = set()
for jar_file in self._find_all_bootstrap_jars():
for cls in self._jar_classfiles(jar_file):
bootstrap_jar_classfiles.add(cls)
return bootstrap_jar_classfiles | [
"def",
"bootstrap_jar_classfiles",
"(",
"self",
")",
":",
"bootstrap_jar_classfiles",
"=",
"set",
"(",
")",
"for",
"jar_file",
"in",
"self",
".",
"_find_all_bootstrap_jars",
"(",
")",
":",
"for",
"cls",
"in",
"self",
".",
"_jar_classfiles",
"(",
"jar_file",
")... | Returns a set of classfiles from the JVM bootstrap jars. | [
"Returns",
"a",
"set",
"of",
"classfiles",
"from",
"the",
"JVM",
"bootstrap",
"jars",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L115-L121 |
224,087 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.compute_transitive_deps_by_target | def compute_transitive_deps_by_target(self, targets):
"""Map from target to all the targets it depends on, transitively."""
# Sort from least to most dependent.
sorted_targets = reversed(sort_targets(targets))
transitive_deps_by_target = defaultdict(set)
# Iterate in dep order, to accumulate the transitive deps for each target.
for target in sorted_targets:
transitive_deps = set()
for dep in target.dependencies:
transitive_deps.update(transitive_deps_by_target.get(dep, []))
transitive_deps.add(dep)
# Need to handle the case where a java_sources target has dependencies.
# In particular if it depends back on the original target.
if hasattr(target, 'java_sources'):
for java_source_target in target.java_sources:
for transitive_dep in java_source_target.dependencies:
transitive_deps_by_target[java_source_target].add(transitive_dep)
transitive_deps_by_target[target] = transitive_deps
return transitive_deps_by_target | python | def compute_transitive_deps_by_target(self, targets):
# Sort from least to most dependent.
sorted_targets = reversed(sort_targets(targets))
transitive_deps_by_target = defaultdict(set)
# Iterate in dep order, to accumulate the transitive deps for each target.
for target in sorted_targets:
transitive_deps = set()
for dep in target.dependencies:
transitive_deps.update(transitive_deps_by_target.get(dep, []))
transitive_deps.add(dep)
# Need to handle the case where a java_sources target has dependencies.
# In particular if it depends back on the original target.
if hasattr(target, 'java_sources'):
for java_source_target in target.java_sources:
for transitive_dep in java_source_target.dependencies:
transitive_deps_by_target[java_source_target].add(transitive_dep)
transitive_deps_by_target[target] = transitive_deps
return transitive_deps_by_target | [
"def",
"compute_transitive_deps_by_target",
"(",
"self",
",",
"targets",
")",
":",
"# Sort from least to most dependent.",
"sorted_targets",
"=",
"reversed",
"(",
"sort_targets",
"(",
"targets",
")",
")",
"transitive_deps_by_target",
"=",
"defaultdict",
"(",
"set",
")",... | Map from target to all the targets it depends on, transitively. | [
"Map",
"from",
"target",
"to",
"all",
"the",
"targets",
"it",
"depends",
"on",
"transitively",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L149-L169 |
224,088 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py | JvmDependencyAnalyzer.resolve_aliases | def resolve_aliases(self, target, scope=None):
"""Resolve aliases in the direct dependencies of the target.
:param target: The direct dependencies of this target are included.
:param scope: When specified, only deps with this scope are included. This is more
than a filter, because it prunes the subgraphs represented by aliases with
un-matched scopes.
:returns: An iterator of (resolved_dependency, resolved_from) tuples.
`resolved_from` is the top level target alias that depends on `resolved_dependency`,
and `None` if `resolved_dependency` is not a dependency of a target alias.
"""
for declared in target.dependencies:
if scope is not None and declared.scope != scope:
# Only `DEFAULT` scoped deps are eligible for the unused dep check.
continue
elif type(declared) in (AliasTarget, Target):
# Is an alias. Recurse to expand.
for r, _ in self.resolve_aliases(declared, scope=scope):
yield r, declared
else:
yield declared, None | python | def resolve_aliases(self, target, scope=None):
for declared in target.dependencies:
if scope is not None and declared.scope != scope:
# Only `DEFAULT` scoped deps are eligible for the unused dep check.
continue
elif type(declared) in (AliasTarget, Target):
# Is an alias. Recurse to expand.
for r, _ in self.resolve_aliases(declared, scope=scope):
yield r, declared
else:
yield declared, None | [
"def",
"resolve_aliases",
"(",
"self",
",",
"target",
",",
"scope",
"=",
"None",
")",
":",
"for",
"declared",
"in",
"target",
".",
"dependencies",
":",
"if",
"scope",
"is",
"not",
"None",
"and",
"declared",
".",
"scope",
"!=",
"scope",
":",
"# Only `DEFA... | Resolve aliases in the direct dependencies of the target.
:param target: The direct dependencies of this target are included.
:param scope: When specified, only deps with this scope are included. This is more
than a filter, because it prunes the subgraphs represented by aliases with
un-matched scopes.
:returns: An iterator of (resolved_dependency, resolved_from) tuples.
`resolved_from` is the top level target alias that depends on `resolved_dependency`,
and `None` if `resolved_dependency` is not a dependency of a target alias. | [
"Resolve",
"aliases",
"in",
"the",
"direct",
"dependencies",
"of",
"the",
"target",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jvm_dependency_analyzer.py#L171-L191 |
224,089 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/ivy_task_mixin.py | IvyTaskMixin.ivy_classpath | def ivy_classpath(self, targets, silent=True, workunit_name=None):
"""Create the classpath for the passed targets.
:API: public
:param targets: A collection of targets to resolve a classpath for.
:type targets: collection.Iterable
"""
result = self._ivy_resolve(targets, silent=silent, workunit_name=workunit_name)
return result.resolved_artifact_paths | python | def ivy_classpath(self, targets, silent=True, workunit_name=None):
result = self._ivy_resolve(targets, silent=silent, workunit_name=workunit_name)
return result.resolved_artifact_paths | [
"def",
"ivy_classpath",
"(",
"self",
",",
"targets",
",",
"silent",
"=",
"True",
",",
"workunit_name",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"_ivy_resolve",
"(",
"targets",
",",
"silent",
"=",
"silent",
",",
"workunit_name",
"=",
"workunit_nam... | Create the classpath for the passed targets.
:API: public
:param targets: A collection of targets to resolve a classpath for.
:type targets: collection.Iterable | [
"Create",
"the",
"classpath",
"for",
"the",
"passed",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/ivy_task_mixin.py#L148-L157 |
224,090 | pantsbuild/pants | src/python/pants/backend/jvm/tasks/ivy_task_mixin.py | IvyTaskMixin._ivy_resolve | def _ivy_resolve(self,
targets,
executor=None,
silent=False,
workunit_name=None,
confs=None,
extra_args=None,
invalidate_dependents=False,
pinned_artifacts=None):
"""Resolves external dependencies for the given targets.
If there are no targets suitable for jvm transitive dependency resolution, an empty result is
returned.
:param targets: The targets to resolve jvm dependencies for.
:type targets: :class:`collections.Iterable` of :class:`pants.build_graph.target.Target`
:param executor: A java executor to run ivy with.
:type executor: :class:`pants.java.executor.Executor`
:param confs: The ivy configurations to resolve; ('default',) by default.
:type confs: :class:`collections.Iterable` of string
:param extra_args: Any extra command line arguments to pass to ivy.
:type extra_args: list of string
:param bool invalidate_dependents: `True` to invalidate dependents of targets that needed to be
resolved.
:returns: The result of the resolve.
:rtype: IvyResolveResult
"""
# If there are no targets, we don't need to do a resolve.
if not targets:
return NO_RESOLVE_RUN_RESULT
confs = confs or ('default',)
fingerprint_strategy = IvyResolveFingerprintStrategy(confs)
with self.invalidated(targets,
invalidate_dependents=invalidate_dependents,
silent=silent,
fingerprint_strategy=fingerprint_strategy) as invalidation_check:
# In case all the targets were filtered out because they didn't participate in fingerprinting.
if not invalidation_check.all_vts:
return NO_RESOLVE_RUN_RESULT
resolve_vts = VersionedTargetSet.from_versioned_targets(invalidation_check.all_vts)
resolve_hash_name = resolve_vts.cache_key.hash
# NB: This used to be a global directory, but is now specific to each task that includes
# this mixin.
ivy_workdir = os.path.join(self.versioned_workdir, 'ivy')
targets = resolve_vts.targets
fetch = IvyFetchStep(confs,
resolve_hash_name,
pinned_artifacts,
self.get_options().soft_excludes,
self.ivy_resolution_cache_dir,
self.ivy_repository_cache_dir,
ivy_workdir)
resolve = IvyResolveStep(confs,
resolve_hash_name,
pinned_artifacts,
self.get_options().soft_excludes,
self.ivy_resolution_cache_dir,
self.ivy_repository_cache_dir,
ivy_workdir)
return self._perform_resolution(fetch, resolve, executor, extra_args, invalidation_check,
resolve_vts, targets, workunit_name) | python | def _ivy_resolve(self,
targets,
executor=None,
silent=False,
workunit_name=None,
confs=None,
extra_args=None,
invalidate_dependents=False,
pinned_artifacts=None):
# If there are no targets, we don't need to do a resolve.
if not targets:
return NO_RESOLVE_RUN_RESULT
confs = confs or ('default',)
fingerprint_strategy = IvyResolveFingerprintStrategy(confs)
with self.invalidated(targets,
invalidate_dependents=invalidate_dependents,
silent=silent,
fingerprint_strategy=fingerprint_strategy) as invalidation_check:
# In case all the targets were filtered out because they didn't participate in fingerprinting.
if not invalidation_check.all_vts:
return NO_RESOLVE_RUN_RESULT
resolve_vts = VersionedTargetSet.from_versioned_targets(invalidation_check.all_vts)
resolve_hash_name = resolve_vts.cache_key.hash
# NB: This used to be a global directory, but is now specific to each task that includes
# this mixin.
ivy_workdir = os.path.join(self.versioned_workdir, 'ivy')
targets = resolve_vts.targets
fetch = IvyFetchStep(confs,
resolve_hash_name,
pinned_artifacts,
self.get_options().soft_excludes,
self.ivy_resolution_cache_dir,
self.ivy_repository_cache_dir,
ivy_workdir)
resolve = IvyResolveStep(confs,
resolve_hash_name,
pinned_artifacts,
self.get_options().soft_excludes,
self.ivy_resolution_cache_dir,
self.ivy_repository_cache_dir,
ivy_workdir)
return self._perform_resolution(fetch, resolve, executor, extra_args, invalidation_check,
resolve_vts, targets, workunit_name) | [
"def",
"_ivy_resolve",
"(",
"self",
",",
"targets",
",",
"executor",
"=",
"None",
",",
"silent",
"=",
"False",
",",
"workunit_name",
"=",
"None",
",",
"confs",
"=",
"None",
",",
"extra_args",
"=",
"None",
",",
"invalidate_dependents",
"=",
"False",
",",
... | Resolves external dependencies for the given targets.
If there are no targets suitable for jvm transitive dependency resolution, an empty result is
returned.
:param targets: The targets to resolve jvm dependencies for.
:type targets: :class:`collections.Iterable` of :class:`pants.build_graph.target.Target`
:param executor: A java executor to run ivy with.
:type executor: :class:`pants.java.executor.Executor`
:param confs: The ivy configurations to resolve; ('default',) by default.
:type confs: :class:`collections.Iterable` of string
:param extra_args: Any extra command line arguments to pass to ivy.
:type extra_args: list of string
:param bool invalidate_dependents: `True` to invalidate dependents of targets that needed to be
resolved.
:returns: The result of the resolve.
:rtype: IvyResolveResult | [
"Resolves",
"external",
"dependencies",
"for",
"the",
"given",
"targets",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/ivy_task_mixin.py#L186-L254 |
224,091 | pantsbuild/pants | src/python/pants/backend/python/tasks/python_execution_task_base.py | PythonExecutionTaskBase.create_pex | def create_pex(self, pex_info=None):
"""Returns a wrapped pex that "merges" the other pexes via PEX_PATH."""
relevant_targets = self.context.targets(
lambda tgt: isinstance(tgt, (
PythonDistribution, PythonRequirementLibrary, PythonTarget, Files)))
with self.invalidated(relevant_targets) as invalidation_check:
# If there are no relevant targets, we still go through the motions of resolving
# an empty set of requirements, to prevent downstream tasks from having to check
# for this special case.
if invalidation_check.all_vts:
target_set_id = VersionedTargetSet.from_versioned_targets(
invalidation_check.all_vts).cache_key.hash
else:
target_set_id = 'no_targets'
interpreter = self.context.products.get_data(PythonInterpreter)
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), target_set_id))
# Note that we check for the existence of the directory, instead of for invalid_vts,
# to cover the empty case.
if not os.path.isdir(path):
pexes = [
self.context.products.get_data(ResolveRequirements.REQUIREMENTS_PEX),
self.context.products.get_data(GatherSources.PYTHON_SOURCES)
]
if self.extra_requirements():
extra_requirements_pex = self.resolve_requirement_strings(
interpreter, self.extra_requirements())
# Add the extra requirements first, so they take precedence over any colliding version
# in the target set's dependency closure.
pexes = [extra_requirements_pex] + pexes
constraints = {constraint for rt in relevant_targets if is_python_target(rt)
for constraint in PythonSetup.global_instance().compatibility_or_constraints(rt)}
with self.merged_pex(path, pex_info, interpreter, pexes, constraints) as builder:
for extra_file in self.extra_files():
extra_file.add_to(builder)
builder.freeze()
return PEX(path, interpreter) | python | def create_pex(self, pex_info=None):
relevant_targets = self.context.targets(
lambda tgt: isinstance(tgt, (
PythonDistribution, PythonRequirementLibrary, PythonTarget, Files)))
with self.invalidated(relevant_targets) as invalidation_check:
# If there are no relevant targets, we still go through the motions of resolving
# an empty set of requirements, to prevent downstream tasks from having to check
# for this special case.
if invalidation_check.all_vts:
target_set_id = VersionedTargetSet.from_versioned_targets(
invalidation_check.all_vts).cache_key.hash
else:
target_set_id = 'no_targets'
interpreter = self.context.products.get_data(PythonInterpreter)
path = os.path.realpath(os.path.join(self.workdir, str(interpreter.identity), target_set_id))
# Note that we check for the existence of the directory, instead of for invalid_vts,
# to cover the empty case.
if not os.path.isdir(path):
pexes = [
self.context.products.get_data(ResolveRequirements.REQUIREMENTS_PEX),
self.context.products.get_data(GatherSources.PYTHON_SOURCES)
]
if self.extra_requirements():
extra_requirements_pex = self.resolve_requirement_strings(
interpreter, self.extra_requirements())
# Add the extra requirements first, so they take precedence over any colliding version
# in the target set's dependency closure.
pexes = [extra_requirements_pex] + pexes
constraints = {constraint for rt in relevant_targets if is_python_target(rt)
for constraint in PythonSetup.global_instance().compatibility_or_constraints(rt)}
with self.merged_pex(path, pex_info, interpreter, pexes, constraints) as builder:
for extra_file in self.extra_files():
extra_file.add_to(builder)
builder.freeze()
return PEX(path, interpreter) | [
"def",
"create_pex",
"(",
"self",
",",
"pex_info",
"=",
"None",
")",
":",
"relevant_targets",
"=",
"self",
".",
"context",
".",
"targets",
"(",
"lambda",
"tgt",
":",
"isinstance",
"(",
"tgt",
",",
"(",
"PythonDistribution",
",",
"PythonRequirementLibrary",
"... | Returns a wrapped pex that "merges" the other pexes via PEX_PATH. | [
"Returns",
"a",
"wrapped",
"pex",
"that",
"merges",
"the",
"other",
"pexes",
"via",
"PEX_PATH",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/python_execution_task_base.py#L86-L127 |
224,092 | pantsbuild/pants | src/python/pants/base/build_environment.py | get_pants_cachedir | def get_pants_cachedir():
"""Return the pants global cache directory."""
# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.
cache_home = os.environ.get('XDG_CACHE_HOME')
if not cache_home:
cache_home = '~/.cache'
return os.path.expanduser(os.path.join(cache_home, 'pants')) | python | def get_pants_cachedir():
# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.
cache_home = os.environ.get('XDG_CACHE_HOME')
if not cache_home:
cache_home = '~/.cache'
return os.path.expanduser(os.path.join(cache_home, 'pants')) | [
"def",
"get_pants_cachedir",
"(",
")",
":",
"# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.",
"cache_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CACHE_HOME'",
")",
"if",
"not",
"cache_home",
":",
"cache_home",
... | Return the pants global cache directory. | [
"Return",
"the",
"pants",
"global",
"cache",
"directory",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/build_environment.py#L37-L43 |
224,093 | pantsbuild/pants | src/python/pants/base/build_environment.py | get_pants_configdir | def get_pants_configdir():
"""Return the pants global config directory."""
# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.
config_home = os.environ.get('XDG_CONFIG_HOME')
if not config_home:
config_home = '~/.config'
return os.path.expanduser(os.path.join(config_home, 'pants')) | python | def get_pants_configdir():
# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.
config_home = os.environ.get('XDG_CONFIG_HOME')
if not config_home:
config_home = '~/.config'
return os.path.expanduser(os.path.join(config_home, 'pants')) | [
"def",
"get_pants_configdir",
"(",
")",
":",
"# Follow the unix XDB base spec: http://standards.freedesktop.org/basedir-spec/latest/index.html.",
"config_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
")",
"if",
"not",
"config_home",
":",
"config_home... | Return the pants global config directory. | [
"Return",
"the",
"pants",
"global",
"config",
"directory",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/build_environment.py#L46-L52 |
224,094 | pantsbuild/pants | src/python/pants/base/build_environment.py | get_scm | def get_scm():
"""Returns the pants Scm if any.
:API: public
"""
# TODO(John Sirois): Extract a module/class to carry the bootstrap logic.
global _SCM
if not _SCM:
from pants.scm.git import Git
# We know about git, so attempt an auto-configure
worktree = Git.detect_worktree()
if worktree and os.path.isdir(worktree):
git = Git(worktree=worktree)
try:
logger.debug('Detected git repository at {} on branch {}'.format(worktree, git.branch_name))
set_scm(git)
except git.LocalException as e:
logger.info('Failed to load git repository at {}: {}'.format(worktree, e))
return _SCM | python | def get_scm():
# TODO(John Sirois): Extract a module/class to carry the bootstrap logic.
global _SCM
if not _SCM:
from pants.scm.git import Git
# We know about git, so attempt an auto-configure
worktree = Git.detect_worktree()
if worktree and os.path.isdir(worktree):
git = Git(worktree=worktree)
try:
logger.debug('Detected git repository at {} on branch {}'.format(worktree, git.branch_name))
set_scm(git)
except git.LocalException as e:
logger.info('Failed to load git repository at {}: {}'.format(worktree, e))
return _SCM | [
"def",
"get_scm",
"(",
")",
":",
"# TODO(John Sirois): Extract a module/class to carry the bootstrap logic.",
"global",
"_SCM",
"if",
"not",
"_SCM",
":",
"from",
"pants",
".",
"scm",
".",
"git",
"import",
"Git",
"# We know about git, so attempt an auto-configure",
"worktree... | Returns the pants Scm if any.
:API: public | [
"Returns",
"the",
"pants",
"Scm",
"if",
"any",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/build_environment.py#L63-L81 |
224,095 | pantsbuild/pants | src/python/pants/base/build_environment.py | set_scm | def set_scm(scm):
"""Sets the pants Scm."""
if scm is not None:
if not isinstance(scm, Scm):
raise ValueError('The scm must be an instance of Scm, given {}'.format(scm))
global _SCM
_SCM = scm | python | def set_scm(scm):
if scm is not None:
if not isinstance(scm, Scm):
raise ValueError('The scm must be an instance of Scm, given {}'.format(scm))
global _SCM
_SCM = scm | [
"def",
"set_scm",
"(",
"scm",
")",
":",
"if",
"scm",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"scm",
",",
"Scm",
")",
":",
"raise",
"ValueError",
"(",
"'The scm must be an instance of Scm, given {}'",
".",
"format",
"(",
"scm",
")",
")",
... | Sets the pants Scm. | [
"Sets",
"the",
"pants",
"Scm",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/build_environment.py#L84-L90 |
224,096 | pantsbuild/pants | src/python/pants/backend/native/tasks/native_compile.py | NativeCompile.get_sources_headers_for_target | def get_sources_headers_for_target(self, target):
"""Return a list of file arguments to provide to the compiler.
NB: result list will contain both header and source files!
:raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources.
"""
# Get source paths relative to the target base so the exception message with the target and
# paths makes sense.
target_relative_sources = target.sources_relative_to_target_base()
rel_root = target_relative_sources.rel_root
# Unique file names are required because we just dump object files into a single directory, and
# the compiler will silently just produce a single object file if provided non-unique filenames.
# TODO: add some shading to file names so we can remove this check.
# NB: It shouldn't matter if header files have the same name, but this will raise an error in
# that case as well. We won't need to do any shading of header file names.
seen_filenames = defaultdict(list)
for src in target_relative_sources:
seen_filenames[os.path.basename(src)].append(src)
duplicate_filename_err_msgs = []
for fname, source_paths in seen_filenames.items():
if len(source_paths) > 1:
duplicate_filename_err_msgs.append("filename: {}, paths: {}".format(fname, source_paths))
if duplicate_filename_err_msgs:
raise self.NativeCompileError(
"Error in target '{}': source files must have a unique filename within a '{}' target. "
"Conflicting filenames:\n{}"
.format(target.address.spec, target.alias(), '\n'.join(duplicate_filename_err_msgs)))
return [os.path.join(get_buildroot(), rel_root, src) for src in target_relative_sources] | python | def get_sources_headers_for_target(self, target):
# Get source paths relative to the target base so the exception message with the target and
# paths makes sense.
target_relative_sources = target.sources_relative_to_target_base()
rel_root = target_relative_sources.rel_root
# Unique file names are required because we just dump object files into a single directory, and
# the compiler will silently just produce a single object file if provided non-unique filenames.
# TODO: add some shading to file names so we can remove this check.
# NB: It shouldn't matter if header files have the same name, but this will raise an error in
# that case as well. We won't need to do any shading of header file names.
seen_filenames = defaultdict(list)
for src in target_relative_sources:
seen_filenames[os.path.basename(src)].append(src)
duplicate_filename_err_msgs = []
for fname, source_paths in seen_filenames.items():
if len(source_paths) > 1:
duplicate_filename_err_msgs.append("filename: {}, paths: {}".format(fname, source_paths))
if duplicate_filename_err_msgs:
raise self.NativeCompileError(
"Error in target '{}': source files must have a unique filename within a '{}' target. "
"Conflicting filenames:\n{}"
.format(target.address.spec, target.alias(), '\n'.join(duplicate_filename_err_msgs)))
return [os.path.join(get_buildroot(), rel_root, src) for src in target_relative_sources] | [
"def",
"get_sources_headers_for_target",
"(",
"self",
",",
"target",
")",
":",
"# Get source paths relative to the target base so the exception message with the target and",
"# paths makes sense.",
"target_relative_sources",
"=",
"target",
".",
"sources_relative_to_target_base",
"(",
... | Return a list of file arguments to provide to the compiler.
NB: result list will contain both header and source files!
:raises: :class:`NativeCompile.NativeCompileError` if there is an error processing the sources. | [
"Return",
"a",
"list",
"of",
"file",
"arguments",
"to",
"provide",
"to",
"the",
"compiler",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_compile.py#L96-L126 |
224,097 | pantsbuild/pants | src/python/pants/backend/native/tasks/native_compile.py | NativeCompile._make_compile_argv | def _make_compile_argv(self, compile_request):
"""Return a list of arguments to use to compile sources. Subclasses can override and append."""
sources_minus_headers = list(self._iter_sources_minus_headers(compile_request))
if len(sources_minus_headers) == 0:
raise self._HeaderOnlyLibrary()
compiler = compile_request.compiler
compiler_options = compile_request.compiler_options
# We are going to execute in the target output, so get absolute paths for everything.
buildroot = get_buildroot()
# TODO: add -v to every compiler and linker invocation!
argv = (
[compiler.exe_filename] +
compiler.extra_args +
# TODO: If we need to produce static libs, don't add -fPIC! (could use Variants -- see #5788).
['-c', '-fPIC'] +
compiler_options +
[
'-I{}'.format(os.path.join(buildroot, inc_dir))
for inc_dir in compile_request.include_dirs
] +
[os.path.join(buildroot, src) for src in sources_minus_headers])
self.context.log.info("selected compiler exe name: '{}'".format(compiler.exe_filename))
self.context.log.debug("compile argv: {}".format(argv))
return argv | python | def _make_compile_argv(self, compile_request):
sources_minus_headers = list(self._iter_sources_minus_headers(compile_request))
if len(sources_minus_headers) == 0:
raise self._HeaderOnlyLibrary()
compiler = compile_request.compiler
compiler_options = compile_request.compiler_options
# We are going to execute in the target output, so get absolute paths for everything.
buildroot = get_buildroot()
# TODO: add -v to every compiler and linker invocation!
argv = (
[compiler.exe_filename] +
compiler.extra_args +
# TODO: If we need to produce static libs, don't add -fPIC! (could use Variants -- see #5788).
['-c', '-fPIC'] +
compiler_options +
[
'-I{}'.format(os.path.join(buildroot, inc_dir))
for inc_dir in compile_request.include_dirs
] +
[os.path.join(buildroot, src) for src in sources_minus_headers])
self.context.log.info("selected compiler exe name: '{}'".format(compiler.exe_filename))
self.context.log.debug("compile argv: {}".format(argv))
return argv | [
"def",
"_make_compile_argv",
"(",
"self",
",",
"compile_request",
")",
":",
"sources_minus_headers",
"=",
"list",
"(",
"self",
".",
"_iter_sources_minus_headers",
"(",
"compile_request",
")",
")",
"if",
"len",
"(",
"sources_minus_headers",
")",
"==",
"0",
":",
"... | Return a list of arguments to use to compile sources. Subclasses can override and append. | [
"Return",
"a",
"list",
"of",
"arguments",
"to",
"use",
"to",
"compile",
"sources",
".",
"Subclasses",
"can",
"override",
"and",
"append",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_compile.py#L193-L220 |
224,098 | pantsbuild/pants | src/python/pants/backend/native/tasks/native_compile.py | NativeCompile._compile | def _compile(self, compile_request):
"""Perform the process of compilation, writing object files to the request's 'output_dir'.
NB: This method must arrange the output files so that `collect_cached_objects()` can collect all
of the results (or vice versa)!
"""
try:
argv = self._make_compile_argv(compile_request)
except self._HeaderOnlyLibrary:
self.context.log.debug('{} is a header-only library'.format(compile_request))
return
compiler = compile_request.compiler
output_dir = compile_request.output_dir
env = compiler.invocation_environment_dict
with self.context.new_workunit(
name=self.workunit_label, labels=[WorkUnitLabel.COMPILER]) as workunit:
try:
process = subprocess.Popen(
argv,
cwd=output_dir,
stdout=workunit.output('stdout'),
stderr=workunit.output('stderr'),
env=env)
except OSError as e:
workunit.set_outcome(WorkUnit.FAILURE)
raise self.NativeCompileError(
"Error invoking '{exe}' with command {cmd} and environment {env} for request {req}: {err}"
.format(exe=compiler.exe_filename, cmd=argv, env=env, req=compile_request, err=e))
rc = process.wait()
if rc != 0:
workunit.set_outcome(WorkUnit.FAILURE)
raise self.NativeCompileError(
"Error in '{section_name}' with command {cmd} and environment {env} for request {req}. "
"Exit code was: {rc}."
.format(section_name=self.workunit_label, cmd=argv, env=env, req=compile_request, rc=rc)) | python | def _compile(self, compile_request):
try:
argv = self._make_compile_argv(compile_request)
except self._HeaderOnlyLibrary:
self.context.log.debug('{} is a header-only library'.format(compile_request))
return
compiler = compile_request.compiler
output_dir = compile_request.output_dir
env = compiler.invocation_environment_dict
with self.context.new_workunit(
name=self.workunit_label, labels=[WorkUnitLabel.COMPILER]) as workunit:
try:
process = subprocess.Popen(
argv,
cwd=output_dir,
stdout=workunit.output('stdout'),
stderr=workunit.output('stderr'),
env=env)
except OSError as e:
workunit.set_outcome(WorkUnit.FAILURE)
raise self.NativeCompileError(
"Error invoking '{exe}' with command {cmd} and environment {env} for request {req}: {err}"
.format(exe=compiler.exe_filename, cmd=argv, env=env, req=compile_request, err=e))
rc = process.wait()
if rc != 0:
workunit.set_outcome(WorkUnit.FAILURE)
raise self.NativeCompileError(
"Error in '{section_name}' with command {cmd} and environment {env} for request {req}. "
"Exit code was: {rc}."
.format(section_name=self.workunit_label, cmd=argv, env=env, req=compile_request, rc=rc)) | [
"def",
"_compile",
"(",
"self",
",",
"compile_request",
")",
":",
"try",
":",
"argv",
"=",
"self",
".",
"_make_compile_argv",
"(",
"compile_request",
")",
"except",
"self",
".",
"_HeaderOnlyLibrary",
":",
"self",
".",
"context",
".",
"log",
".",
"debug",
"... | Perform the process of compilation, writing object files to the request's 'output_dir'.
NB: This method must arrange the output files so that `collect_cached_objects()` can collect all
of the results (or vice versa)! | [
"Perform",
"the",
"process",
"of",
"compilation",
"writing",
"object",
"files",
"to",
"the",
"request",
"s",
"output_dir",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_compile.py#L222-L260 |
224,099 | pantsbuild/pants | src/python/pants/backend/native/tasks/native_compile.py | NativeCompile.collect_cached_objects | def collect_cached_objects(self, versioned_target):
"""Scan `versioned_target`'s results directory and return the output files from that directory.
:return: :class:`ObjectFiles`
"""
return ObjectFiles(versioned_target.results_dir, os.listdir(versioned_target.results_dir)) | python | def collect_cached_objects(self, versioned_target):
return ObjectFiles(versioned_target.results_dir, os.listdir(versioned_target.results_dir)) | [
"def",
"collect_cached_objects",
"(",
"self",
",",
"versioned_target",
")",
":",
"return",
"ObjectFiles",
"(",
"versioned_target",
".",
"results_dir",
",",
"os",
".",
"listdir",
"(",
"versioned_target",
".",
"results_dir",
")",
")"
] | Scan `versioned_target`'s results directory and return the output files from that directory.
:return: :class:`ObjectFiles` | [
"Scan",
"versioned_target",
"s",
"results",
"directory",
"and",
"return",
"the",
"output",
"files",
"from",
"that",
"directory",
"."
] | b72e650da0df685824ffdcc71988b8c282d0962d | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/native/tasks/native_compile.py#L262-L267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.