code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
yprint(build_context.conf, 'Build CppApp', target)
if target.props.executable and target.props.main:
raise KeyError(
'`main` and `executable` arguments are mutually exclusive')
if target.props.executable:
if target.props.executable not in target.artifacts.get(AT.app):
... | def cpp_app_builder(build_context, target) | Pack a C++ binary as a Docker image with its runtime dependencies.
TODO(itamar): Dynamically analyze the binary and copy shared objects
from its buildenv image to the runtime image, unless they're installed. | 4.045774 | 3.934578 | 1.028261 |
def pre_build_hook(build_context, target):
target.compiler_config = CompilerConfig(
build_context, target, extra_compiler_config_params)
target.props._internal_dict_['compiler_config'] = (
target.compiler_config.as_dict())
return pre_build_hook | def make_pre_build_hook(extra_compiler_config_params) | Return a pre-build hook function for C++ builders.
When called, during graph build, it computes and stores the compiler-config
object on the target, as well as adding it to the internal_dict prop for
hashing purposes. | 4.530601 | 3.340241 | 1.356369 |
objects = []
for src in sources:
obj_rel_path = '{}.o'.format(splitext(src)[0])
obj_file = join(buildenv_workspace, obj_rel_path)
include_paths = [buildenv_workspace] + compiler_config.include_path
compile_cmd = (
[compiler_config.compiler, '-o', obj_file, '-c'] ... | def compile_cc(build_context, compiler_config, buildenv, sources,
workspace_dir, buildenv_workspace, cmd_env) | Compile list of C++ source files in a buildenv image
and return list of generated object file. | 3.947654 | 3.897722 | 1.012811 |
# include the source & header files of the current target
# add objects of all dependencies (direct & transitive), if needed
source_files = target.props.sources + target.props.headers
generated_srcs = {}
objects = []
# add headers of dependencies
for dep in build_context.generate_all_d... | def link_cpp_artifacts(build_context, target, workspace_dir,
include_objects: bool) | Link required artifacts from dependencies under target workspace dir.
Return list of object files of dependencies (if `include_objects`).
Includes:
- Generated code from proto dependencies
- Header files from all dependencies
- Generated header files from all dependencies
- If `include_objec... | 4.614817 | 4.238288 | 1.08884 |
all_sources = list(target.props.sources)
for proto_dep_name in target.props.protos:
proto_dep = build_context.targets[proto_dep_name]
all_sources.extend(proto_dep.artifacts.get(AT.gen_cc).keys())
return all_sources | def get_source_files(target, build_context) -> list | Return list of source files for `target`. | 6.280416 | 5.594218 | 1.122662 |
rmtree(workspace_dir)
binary = join(*split(target.name))
objects = link_cpp_artifacts(build_context, target, workspace_dir, True)
buildenv_workspace = build_context.conf.host_to_buildenv_path(
workspace_dir)
objects.extend(compile_cc(
build_context, compiler_config, target.props... | def build_cpp(build_context, target, compiler_config, workspace_dir) | Compile and link a C++ binary for `target`. | 4.633143 | 4.535164 | 1.021604 |
yprint(build_context.conf, 'Build CppProg', target)
workspace_dir = build_context.get_workspace('CppProg', target.name)
build_cpp(build_context, target, target.compiler_config, workspace_dir) | def cpp_prog_builder(build_context, target) | Build a C++ binary executable | 7.863738 | 7.523756 | 1.045188 |
yprint(build_context.conf, 'Build CppLib', target)
workspace_dir = build_context.get_workspace('CppLib', target.name)
workspace_src_dir = join(workspace_dir, 'src')
rmtree(workspace_src_dir)
link_cpp_artifacts(build_context, target, workspace_src_dir, False)
buildenv_workspace = build_conte... | def cpp_lib_builder(build_context, target) | Build C++ object files | 5.064232 | 4.977964 | 1.01733 |
target_val = target.props.get(param)
config_val = config.get(param, fallback)
if not target_val:
return config_val
if isinstance(target_val, list):
val = []
for el in target_val:
if el == '$*':
val.extend(li... | def get(self, param, config, target, fallback) | Return the value of `param`, according to priority / expansion.
First priority - the target itself.
Second priority - the project config.
Third priority - a global default ("fallback").
In list-params, a '$*' term processed as "expansion term", meaning
it is replaced with all t... | 2.638383 | 2.623444 | 1.005694 |
for license_name in target.props.license:
if license_name not in KNOWN_LICENSES:
# TODO: include suggestion for similar known license
return 'Unknown license: {}'.format(license_name)
return None | def standard_licenses_only(build_context, target) -> str | A policy function for allowing specifying only known licenses.
Return error message (string) if policy for `target` is violated,
otherwise return `None`.
To apply in project, include this function in the ilst returned by the
`get_policies` function implemented in the project `YSettings` file.
See... | 7.131671 | 7.543906 | 0.945355 |
def policy_func(build_context, target):
if policy_name in target.props.policies:
licenses = set(target.props.license)
for dep in build_context.generate_all_deps(target):
licenses.update(dep.props.license)
licenses.difference_update(allowed_l... | def whitelist_licenses_policy(policy_name: str, allowed_licenses: set) | A policy factory for making license-based whitelist policies.
To apply in project, include the function returned from this factory
in the ilst returned by the `get_policies` function implemented in the
project `YSettings` file.
The factory returns a policy function named
`whitelist_{policy_name}_l... | 3.710996 | 3.053123 | 1.215476 |
if project_root:
project_config_file = os.path.join(project_root, YCONFIG_FILE)
if os.path.isfile(project_config_file):
return project_config_file | def find_project_config_file(project_root: str) -> str | Return absolute path to project-specific config file, if it exists.
:param project_root: Absolute path to project root directory.
A project config file is a file named `YCONFIG_FILE` found at the top
level of the project root dir.
Return `None` if project root dir is not specified,
or if no such ... | 2.820898 | 1.899911 | 1.484753 |
if project_root:
project_settings_file = os.path.join(project_root, YSETTINGS_FILE)
if os.path.isfile(project_settings_file):
settings_loader = SourceFileLoader(
'settings', project_settings_file)
return settings_loader.load_module() | def get_user_settings_module(project_root: str) | Return project-specific user settings module, if it exists.
:param project_root: Absolute path to project root directory.
A project settings file is a file named `YSETTINGS_FILE` found at the top
level of the project root dir.
Return `None` if project root dir is not specified,
or if no such file... | 3.124941 | 2.549164 | 1.225869 |
if settings_module:
if hasattr(settings_module, func_name):
func = getattr(settings_module, func_name)
try:
return func(*args, **kwargs)
finally:
# cleanup user function
delattr(settings_module, func_name) | def call_user_func(settings_module, func_name, *args, **kwargs) | Call a user-supplied settings function and clean it up afterwards.
settings_module may be None, or the function may not exist.
If the function exists, it is called with the specified *args and **kwargs,
and the result is returned. | 2.259074 | 2.429139 | 0.92999 |
known_flavors = listify(call_user_func(settings_module, 'known_flavors'))
if args.flavor:
if args.flavor not in known_flavors:
raise ValueError('Unknown build flavor: {}'.format(args.flavor))
else:
args.flavor = call_user_func(settings_module, 'default_flavor')
if ar... | def get_build_flavor(settings_module, args) | Update the flavor arg based on the settings API | 2.284574 | 2.317762 | 0.985681 |
colorama.init()
work_dir = os.path.abspath(os.curdir)
project_root = search_for_parent_dir(work_dir,
with_files=set([BUILD_PROJ_FILE]))
parser = make_parser(find_project_config_file(project_root))
settings_module = get_user_settings_module(project_root)
... | def init_and_get_conf(argv: list=None) -> Config | Initialize a YABT CLI environment and return a Config instance.
:param argv: Manual override of command-line params to parse (for tests). | 3.758433 | 3.828506 | 0.981697 |
if not graph.is_directed():
raise networkx.NetworkXError(
'Topological sort not defined on undirected graphs.')
# nonrecursive version
seen = set()
explored = set()
for v in sorted(graph.nodes()):
if v in explored:
continue
fringe = [v] # nodes... | def stable_reverse_topological_sort(graph) | Return a list of nodes in topological sort order.
This topological sort is a **unique** permutation of the nodes
such that an edge from u to v implies that u appears before v in the
topological sort order.
Parameters
----------
graph : NetworkX digraph
A directed graph
Raises
... | 3.216069 | 3.329737 | 0.965863 |
def format_target(target_name):
# TODO: suggest similar known target names
build_module = split_build_module(target_name)
return '{} (in {})'.format(target_name,
conf.get_build_file_path(build_module))
def format_unresolved(seed):
if seed... | def raise_unresolved_targets(build_context, conf, unknown_seeds, seed_refs) | Raise error about unresolved targets during graph parsing. | 2.754622 | 2.814039 | 0.978886 |
def register_decorator(scm_class: SourceControl):
if scm_name in ScmManager.providers:
raise KeyError('{} already registered!'.format(scm_name))
ScmManager.providers[scm_name] = scm_class
SourceControl.register(scm_class)
logger.debug('Registered {0} SCM fr... | def register_scm_provider(scm_name: str) | Return a decorator for registering a SCM provider named `scm_name`. | 3.831698 | 3.191703 | 1.200519 |
for entry_point in pkg_resources.iter_entry_points('yabt.scm',
scm_name):
entry_point.load()
logger.debug('Loaded SCM provider {0.name} from {0.module_name} '
'(dist {0.dist})', entry_point)
... | def get_provider(cls, scm_name: str, conf) -> SourceControl | Load and return named SCM provider instance.
:param conf: A yabt.config.Config object used to initialize the SCM
provider instance.
:raises KeyError: If no SCM provider with name `scm_name` registered. | 3.095751 | 3.117474 | 0.993032 |
not_buildenv_targets = get_not_buildenv_targets(build_context)
prebuilt_targets = get_prebuilt_targets(build_context)
out_f.write('strict digraph {\n')
for node in build_context.target_graph.nodes:
if conf.show_buildenv_deps or node in not_buildenv_targets:
cached = node in pre... | def write_dot(build_context, conf: Config, out_f) | Write build graph in dot format to `out_f` file-like object. | 3.068328 | 2.975233 | 1.03129 |
workspace_dir = os.path.join(self.conf.get_workspace_path(),
*(get_safe_path(part) for part in parts))
if not os.path.isdir(workspace_dir):
# exist_ok=True in case of concurrent creation of the same dir
os.makedirs(workspace_dir, exis... | def get_workspace(self, *parts) -> str | Return a path to a private workspace dir.
Create sub-tree of dirs using strings from `parts` inside workspace,
and return full path to innermost directory.
Upon returning successfully, the directory will exist (potentially
changed to a safe FS name), even if it didn't exist before... | 3.728884 | 3.29523 | 1.131601 |
bin_dir = os.path.join(self.conf.get_bin_path(), build_module)
if not os.path.isdir(bin_dir):
# exist_ok=True in case of concurrent creation of the same dir
os.makedirs(bin_dir, exist_ok=True)
return bin_dir | def get_bin_dir(self, build_module: str) -> str | Return a path to the binaries dir for a build module dir.
Create sub-tree of missing dirs as needed, and return full path
to innermost directory. | 3.408489 | 2.964622 | 1.149721 |
all_deps = get_descendants(self.target_graph, target.name)
for dep_name in topological_sort(self.target_graph):
if dep_name in all_deps:
yield self.targets[dep_name] | def walk_target_deps_topological_order(self, target: Target) | Generate all dependencies of `target` by topological sort order. | 4.423337 | 3.493643 | 1.26611 |
yield from (self.targets[dep_name] for dep_name in sorted(target.deps)) | def generate_direct_deps(self, target: Target) | Generate only direct dependencies of `target`. | 9.949585 | 5.662511 | 1.757098 |
yield from sorted(get_descendants(self.target_graph, target.name)) | def generate_dep_names(self, target: Target) | Generate names of all dependencies (descendants) of `target`. | 19.84446 | 8.793907 | 2.256615 |
yield from (self.targets[dep_name]
for dep_name in self.generate_dep_names(target)) | def generate_all_deps(self, target: Target) | Generate all dependencies of `target` (the target nodes). | 8.332203 | 5.671042 | 1.469254 |
if target.name in self.targets:
first = self.targets[target.name]
raise NameError(
'Target with name "{0.name}" ({0.builder_name} from module '
'"{1}") already exists - defined first as '
'{2.builder_name} in module "{3}"'.format(
... | def register_target(self, target: Target) | Register a `target` instance in this build context.
A registered target is saved in the `targets` map and in the
`targets_by_module` map, but is not added to the target graph until
target extraction is completed (thread safety considerations). | 3.936081 | 3.528973 | 1.115361 |
if target_name in self.targets:
del self.targets[target_name]
build_module = split_build_module(target_name)
if build_module in self.targets_by_module:
self.targets_by_module[build_module].remove(target_name) | def remove_target(self, target_name: str) | Remove (unregister) a `target` from this build context.
Removes the target instance with the given name, if it exists,
from both the `targets` map and the `targets_by_module` map.
Doesn't do anything if no target with that name is found.
Doesn't touch the target graph, if it exists. | 3.177876 | 2.763752 | 1.149841 |
extraction_context = {}
for name, builder in Plugin.builders.items():
extraction_context[name] = extractor(name, builder,
build_file_path, self)
return extraction_context | def get_target_extraction_context(self, build_file_path: str) -> dict | Return a build file parser target extraction context.
The target extraction context is a build-file-specific mapping from
builder-name to target extraction function,
for every registered builder. | 6.739735 | 5.40252 | 1.247517 |
# This implementation first obtains all subsets of nodes that all
# buildenvs depend on, and then builds a subgraph induced by the union
# of these subsets. This can be very non-optimal.
# TODO(itamar): Reimplement efficient algo, or redesign buildenvs
buildenvs = set(ta... | def get_buildenv_graph(self) | Return a graph induced by buildenv nodes | 7.328696 | 6.716769 | 1.091104 |
def is_ready(target_name):
try:
next(graph_copy.successors(target_name))
except StopIteration:
return True
return False
ready_nodes = deque(sorted(
target_name for target_name in graph_copy.nodes
... | def ready_nodes_iter(self, graph_copy) | Generate ready targets from the graph `graph_copy`.
The input graph is mutated by this method, so it has to be a mutable
copy of the graph (e.g. not original copy, or read-only view).
Caller **must** call `done()` after processing every generated
target, so additional ready targets can... | 3.045962 | 2.994409 | 1.017216 |
builder = Plugin.builders[target.builder_name]
if builder.func:
logger.debug('About to invoke the {} builder function for {}',
target.builder_name, target.name)
builder.func(self, target)
else:
logger.debug('Skipping {} builde... | def build_target(self, target: Target) | Invoke the builder function for a target. | 4.906609 | 3.807434 | 1.288692 |
with self.context_lock:
self.artifacts_metadata[target.name] = metadata | def register_target_artifact_metadata(self, target: str, metadata: dict) | Register the artifact metadata dictionary for a built target. | 11.026218 | 7.626748 | 1.44573 |
if self.conf.artifacts_metadata_file:
logger.info('Writing artifacts metadata to file "%s"',
self.conf.artifacts_metadata_file)
with open(self.conf.artifacts_metadata_file, 'w') as fp:
json.dump(self.artifacts_metadata, fp) | def write_artifacts_metadata(self) | Write out a JSON file with all built targets artifact metadata,
if such output file is specified. | 2.296506 | 2.125606 | 1.080401 |
# if caching is disabled for this execution, then all targets are dirty
if self.conf.no_build_cache:
return False
# if the target's `cachable` prop is falsy, then it is dirty
if not target.props.cachable:
return False
# if any dependency of the ta... | def can_use_cache(self, target: Target) -> bool | Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty). | 4.411222 | 4.087711 | 1.079142 |
project_root = Path(self.project_root)
build_module = norm_proj_path(build_module, '')
return str(project_root / build_module /
(BUILD_PROJ_FILE if '' == build_module
else self.build_file_name)) | def get_build_file_path(self, build_module) -> str | Return a full path to the build file of `build_module`.
The returned path will always be OS-native, regardless of the format
of project_root (native) and build_module (with '/'). | 6.942977 | 6.140038 | 1.130771 |
# TODO(itamar): do this better
if hint:
return hint
norm_uri = uri.lower()
parsed_uri = urlparse(norm_uri)
if parsed_uri.path.endswith('.git'):
return 'git'
if parsed_uri.scheme in ('http', 'https'):
ext = splitext(parsed_uri.path)[-1]
if ext in KNOWN_ARCHIVE... | def guess_uri_type(uri: str, hint: str=None) | Return a guess for the URI type based on the URI string `uri`.
If `hint` is given, it is assumed to be the correct type.
Otherwise, the URI is inspected using urlparse, and we try to guess
whether it's a remote Git repository, a remote downloadable archive,
or a local-only data. | 3.677416 | 3.188281 | 1.153416 |
target_name = split_name(target.name)
# clone the repository under a private builder workspace
repo_dir = join(package_dir, fetch.name) if fetch.name else package_dir
try:
repo = git.Repo(repo_dir)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = git.Repo.clone_from(f... | def git_handler(unused_build_context, target, fetch, package_dir, tar) | Handle remote Git repository URI.
Clone the repository under the private builder workspace (unless already
cloned), and add it to the package tar (filtering out git internals).
TODO(itamar): Support branches / tags / specific commit hashes
TODO(itamar): Support updating a cloned repository
TODO(it... | 3.986257 | 3.586005 | 1.111615 |
logger.debug('Downloading file {} from {}', dest, url)
try:
shutil.rmtree(parent_to_remove_before_fetch)
except FileNotFoundError:
pass
os.makedirs(parent_to_remove_before_fetch)
# TODO(itamar): Better downloading (multi-process-multi-threaded?)
# Consider offloading this to... | def fetch_url(url, dest, parent_to_remove_before_fetch) | Helper function to fetch a file from a URL. | 4.067902 | 4.16619 | 0.976408 |
package_dest = join(package_dir, basename(urlparse(fetch.uri).path))
package_content_dir = join(package_dir, 'content')
extract_dir = (join(package_content_dir, fetch.name)
if fetch.name else package_content_dir)
fetch_url(fetch.uri, package_dest, package_dir)
# TODO(itamar)... | def archive_handler(unused_build_context, target, fetch, package_dir, tar) | Handle remote downloadable archive URI.
Download the archive and cache it under the private builer workspace
(unless already downloaded), extract it, and add the content to the
package tar.
TODO(itamar): Support re-downloading if remote changed compared to local.
TODO(itamar): Support more archive... | 3.623852 | 3.514461 | 1.031126 |
dl_dir = join(package_dir, fetch.name) if fetch.name else package_dir
fetch_url(fetch.uri,
join(dl_dir, basename(urlparse(fetch.uri).path)),
dl_dir)
tar.add(package_dir, arcname=split_name(target.name)) | def fetch_file_handler(unused_build_context, target, fetch, package_dir, tar) | Handle remote downloadable file URI.
Download the file and cache it under the private builer workspace
(unless already downloaded), and add it to the package tar.
TODO(itamar): Support re-downloading if remote changed compared to local. | 4.375669 | 4.449501 | 0.983407 |
workspace_dir = build_context.get_workspace('CustomInstaller', target.name)
target_name = split_name(target.name)
script_name = basename(target.props.script)
package_tarball = '{}.tar.gz'.format(join(workspace_dir, target_name))
return target_name, script_name, package_tarball | def get_installer_desc(build_context, target) -> tuple | Return a target_name, script_name, package_tarball tuple for `target` | 5.702653 | 3.619534 | 1.575522 |
logger.info('Scanning for cached base images')
# deps that are part of cached based images
contained_deps = set()
# deps that are needed by images that are going to be built,
# but are not part of their base images
required_deps = set()
# mapping from target name to set of all its deps ... | def get_prebuilt_targets(build_context) | Return set of target names that are contained within cached base images
These targets may be considered "pre-built", and skipped during build. | 3.75468 | 3.620429 | 1.037082 |
# update the summary last-accessed timestamp
summary['accessed'] = time()
with open(join(cache_dir, 'summary.json'), 'w') as summary_file:
summary_file.write(json.dumps(summary, indent=4, sort_keys=True)) | def write_summary(summary: dict, cache_dir: str) | Write the `summary` JSON to `cache_dir`.
Updated the accessed timestamp to now before writing. | 3.518588 | 2.805921 | 1.253987 |
cache_dir = build_context.conf.get_cache_dir(target, build_context)
if not isdir(cache_dir):
logger.debug('No cache dir found for target {}', target.name)
return False, False
# read summary file and restore relevant fields into target
with open(join(cache_dir, 'summary.json'), 'r') ... | def load_target_from_cache(target: Target, build_context) -> (bool, bool) | Load `target` from build cache, restoring cached artifacts & summary.
Return (build_cached, test_cached) tuple.
`build_cached` is True if target restored successfully.
`test_cached` is True if build is cached and test_time metadata is valid. | 3.124902 | 3.078719 | 1.015001 |
cache_dir = conf.get_artifacts_cache_dir()
if not isdir(cache_dir):
makedirs(cache_dir)
cached_artifact_path = join(cache_dir, artifact_hash)
if isfile(cached_artifact_path) or isdir(cached_artifact_path):
logger.debug('Skipping copy of existing cached artifact {} -> {}',
... | def copy_artifact(src_path: str, artifact_hash: str, conf: Config) | Copy the artifact at `src_path` with hash `artifact_hash` to artifacts
cache dir.
If an artifact already exists at that location, it is assumed to be
identical (since it's based on hash), and the copy is skipped.
TODO: pruning policy to limit cache size. | 2.41401 | 2.258092 | 1.069048 |
cache_dir = conf.get_artifacts_cache_dir()
if not isdir(cache_dir):
return False
cached_artifact_path = join(cache_dir, artifact_hash)
if isfile(cached_artifact_path) or isdir(cached_artifact_path):
# verify cached item hash matches expected hash
actual_hash = hash_tree(cach... | def restore_artifact(src_path: str, artifact_hash: str, conf: Config) | Restore the artifact whose hash is `artifact_hash` to `src_path`.
Return True if cached artifact is found, valid, and restored successfully.
Otherwise return False. | 2.480853 | 2.39462 | 1.036011 |
cache_dir = build_context.conf.get_cache_dir(target, build_context)
if isdir(cache_dir):
rmtree(cache_dir)
makedirs(cache_dir)
logger.debug('Saving target metadata in cache under {}', cache_dir)
# write target metadata
with open(join(cache_dir, 'target.json'), 'w') as meta_file:
... | def save_target_in_cache(target: Target, build_context) | Save `target` to build cache for future reuse.
The target hash is used to determine its cache location,
where the target metadata and artifacts metadata are seriazlied to JSON.
In addition, relevant artifacts produced by the target are copied under
the artifacts cache dir by their content hash.
TO... | 2.99428 | 2.925387 | 1.02355 |
if key not in self:
self[key] = set(get_descendants(self._target_graph, key))
return self[key] | def get(self, key) | Return set of descendants of node named `key` in `target_graph`.
Returns from cached dict if exists, otherwise compute over the graph
and cache results in the dict. | 6.550912 | 3.349208 | 1.955958 |
exc_str = format_exc()
if exc_str.strip() != 'NoneType: None':
logger.info('{}', format_exc())
fatal_noexc(msg, *args, **kwargs) | def fatal(msg, *args, **kwargs) | Print a red `msg` to STDERR and exit.
To be used in a context of an exception, also prints out the exception.
The message is formatted with `args` & `kwargs`. | 6.530344 | 6.638612 | 0.983691 |
print(Fore.RED + 'Fatal: ' + msg.format(*args, **kwargs) + Style.RESET_ALL,
file=sys.stderr)
sys.exit(1) | def fatal_noexc(msg, *args, **kwargs) | Print a red `msg` to STDERR and exit.
The message is formatted with `args` & `kwargs`. | 2.860792 | 2.855369 | 1.001899 |
if isdir(path):
rmtree(path)
elif isfile(path):
os.remove(path) | def rmnode(path: str) | Forcibly remove file or directory tree at `path`.
Fail silently if base dir doesn't exist. | 3.291607 | 3.009759 | 1.093645 |
dest_parent_dir = split(abs_dest)[0]
if not isdir(dest_parent_dir):
# exist_ok=True in case of concurrent creation of the same
# parent dir
os.makedirs(dest_parent_dir, exist_ok=True)
if isfile(abs_src):
# sync file by linking it to dest
link_func(abs_src, abs_de... | def link_node(abs_src: str, abs_dest: str, force: bool=False) | Sync source node (file / dir) to destination path using hard links. | 3.111753 | 2.949489 | 1.055014 |
norm_dir = normpath(workspace_src_dir)
base_dir = ''
if common_parent:
common_parent = normpath(common_parent)
base_dir = commonpath(list(files) + [common_parent])
if base_dir != common_parent:
raise ValueError('{} is not the common parent of all target '
... | def link_files(files: set, workspace_src_dir: str,
common_parent: str, conf) | Sync the list of files and directories in `files` to destination
directory specified by `workspace_src_dir`.
"Sync" in the sense that every file given in `files` will be
hard-linked under `workspace_src_dir` after this function returns, and no
other files will exist under `workspace_src_dir`.
F... | 4.206404 | 3.885563 | 1.082573 |
if path == '//':
return ''
if path.startswith('//'):
norm = normpath(path[2:])
if norm[0] in ('.', '/', '\\'):
raise ValueError("Invalid path: `{}'".format(path))
return norm
if path.startswith('/'):
raise ValueError("Invalid path: `{}' - use '//' t... | def norm_proj_path(path, build_module) | Return a normalized path for the `path` observed in `build_module`.
The normalized path is "normalized" (in the `os.path.normpath` sense),
relative from the project root directory, and OS-native.
Supports making references from project root directory by prefixing the
path with "//".
:raises Value... | 3.714525 | 3.494816 | 1.062867 |
if not start_at:
start_at = os.path.abspath(os.curdir)
if not with_files:
with_files = set()
if not with_dirs:
with_dirs = set()
exp_hits = len(with_files) + len(with_dirs)
while start_at:
num_hits = 0
for entry in scandir(start_at):
if ((entr... | def search_for_parent_dir(start_at: str=None, with_files: set=None,
with_dirs: set=None) -> str | Return absolute path of first parent directory of `start_at` that
contains all files `with_files` and all dirs `with_dirs`
(including `start_at`).
If `start_at` not specified, start at current working directory.
:param start_at: Initial path for searching for the project build file.
Returns... | 2.257954 | 2.321531 | 0.972614 |
with open(filepath, 'rb') as f:
while True:
chunk = f.read(_BUF_SIZE)
if not chunk:
break
hasher.update(chunk) | def acc_hash(filepath: str, hasher) | Accumulate content of file at `filepath` in `hasher`. | 2.412057 | 2.130059 | 1.13239 |
md5 = hashlib.md5()
acc_hash(filepath, md5)
return md5.hexdigest() | def hash_file(filepath: str) -> str | Return the hexdigest MD5 hash of content of file at `filepath`. | 7.749458 | 5.343905 | 1.450149 |
if isfile(filepath):
return hash_file(filepath)
if isdir(filepath):
base_dir = filepath
md5 = hashlib.md5()
for root, dirs, files in walk(base_dir):
dirs.sort()
for fname in sorted(files):
filepath = join(root, fname)
#... | def hash_tree(filepath: str) -> str | Return the hexdigest MD5 hash of file or directory at `filepath`.
If file - just hash file content.
If directory - walk the directory, and accumulate hashes of all the
relative paths + contents of files under the directory. | 3.528149 | 3.343252 | 1.055305 |
if dst_path is None:
dst_path = src_path
other_src_path = self._artifacts[artifact_type].setdefault(
dst_path, src_path)
if src_path != other_src_path:
raise RuntimeError(
'{} artifact with dest path {} exists with different src '
... | def add(self, artifact_type: ArtifactType, src_path: str,
dst_path: str=None) | Add an artifact of type `artifact_type` at `src_path`.
`src_path` should be the path of the file relative to project root.
`dst_path`, if given, is the desired path of the artifact in dependent
targets, relative to its base path (by type). | 3.246195 | 3.330971 | 0.974549 |
for src_path in src_paths:
self.add(artifact_type, src_path, src_path) | def extend(self, artifact_type: ArtifactType, src_paths: list) | Add all `src_paths` as artifact of type `artifact_type`. | 3.955888 | 2.471597 | 1.600539 |
num_linked = 0
for kind in types:
artifact_map = self._artifacts.get(kind)
if not artifact_map:
continue
num_linked += self._link(join(base_dir, self.type_to_dir[kind]),
artifact_map, conf)
return n... | def link_types(self, base_dir: str, types: list, conf: Config) -> int | Link all artifacts with types `types` under `base_dir` and return
the number of linked artifacts. | 4.382146 | 3.567191 | 1.228458 |
return self.link_types(
base_dir,
[ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py],
conf) | def link_for_image(self, base_dir: str, conf: Config) -> int | Link all artifacts required for a Docker image under `base_dir` and
return the number of linked artifacts. | 14.710382 | 9.399469 | 1.565023 |
num_linked = 0
for dst, src in artifact_map.items():
abs_src = join(conf.project_root, src)
abs_dest = join(conf.project_root, base_dir, dst)
link_node(abs_src, abs_dest)
num_linked += 1
return num_linked | def _link(self, base_dir: str, artifact_map: dict, conf: Config) | Link all artifacts in `artifact_map` under `base_dir` and return
the number of artifacts linked. | 3.143391 | 2.43384 | 1.291535 |
base_dir = path.abspath(path.dirname(__file__))
with open(path.join(base_dir, 'README.md'), encoding='utf-8') as readme_f:
return readme_f.read() | def get_readme() | Read and return the content of the project README file. | 2.188908 | 2.00678 | 1.090756 |
if len(args) > len(builder.sig):
# too many positional arguments supplied - say how many we can take
raise TypeError('{}() takes {}, but {} were given'
.format(target.builder_name,
format_num_positional_arguments(builder),
... | def args_to_props(target: Target, builder: Builder, args: list, kwargs: dict) | Convert build file `args` and `kwargs` to `target` props.
Use builder signature to validate builder usage in build-file, raising
appropriate exceptions on signature-mismatches.
Use builder signature default values to assign props values to args that
were not passed in the build-file call.
This fu... | 3.431346 | 3.35934 | 1.021434 |
build_module = to_build_module(build_file_path, build_context.conf)
def extract_target(*args, **kwargs):
target = Target(builder_name=builder_name)
# convert args/kwargs to target.props and handle arg types
args_to_props(target, builder, args, kwargs)
raw_name = ta... | def extractor(
builder_name: str, builder: Builder, build_file_path: str,
build_context) -> types.FunctionType | Return a target extraction function for a specific builder and a
specific build file. | 4.39414 | 4.352567 | 1.009551 |
aman = ActionManager()
# assume all actions.* modules are action modules
aman.add_actions_modules(actions)
aman.fill_aliases()
# additional rdopkg action module logic should go here
return ActionRunner(action_manager=aman) | def rdopkg_runner() | default rdopkg action runner including rdopkg action modules | 15.703574 | 11.178106 | 1.404851 |
runner = rdopkg_runner()
return shell.run(runner,
cargs=cargs,
prog='rdopkg',
version=__version__) | def rdopkg(*cargs) | rdopkg CLI interface
Execute rdopkg action with specified arguments and return
shell friendly exit code.
This is the default high level way to interact with rdopkg.
py> rdopkg('new-version', '1.2.3')
is equivalent to
$> rdopkg new-version 1.2.3 | 6.986677 | 9.628279 | 0.725641 |
initparams = {}
if "interval" in config:
initparams["detect_interval"] = config["interval"]
if plugins is not None:
initparams["plugins"] = plugins
if "updater" in config:
for updater_name, updater_options in config["updater"]:
initparams["updater"] = get_updat... | def getDynDnsClientForConfig(config, plugins=None) | Instantiate and return a complete and working dyndns client.
:param config: a dictionary with configuration keys
:param plugins: an object that implements PluginManager | 3.520665 | 3.732323 | 0.943291 |
detected_ip = self.detector.detect()
if detected_ip is None:
LOG.debug("Couldn't detect the current IP using detector %r", self.detector.names()[-1])
# we don't have a value to set it to, so don't update! Still shouldn't happen though
elif self.dns.detect() != de... | def sync(self) | Synchronize the registered IP with the detected IP (if needed).
This can be expensive, mostly depending on the detector, but also
because updating the dynamic ip in itself is costly. Therefore, this
method should usually only be called on startup or when the state changes. | 5.146549 | 4.665422 | 1.103126 |
self.lastcheck = time.time()
# prefer offline state change detection:
if self.detector.can_detect_offline():
self.detector.detect()
elif not self.dns.detect() == self.detector.get_current_value():
# The following produces traffic, but probably less traffi... | def has_state_changed(self) | Detect changes in offline detector and real DNS value.
Detect a change either in the offline detector or a
difference between the real DNS value and what the online
detector last got.
This is efficient, since it only generates minimal dns traffic
for online detectors and no traf... | 8.068478 | 6.216063 | 1.298004 |
if self.lastcheck is None:
return True
return time.time() - self.lastcheck >= self.ipchangedetection_sleep | def needs_check(self) | Check if enough time has elapsed to perform a check().
If this time has elapsed, a state change check through
has_state_changed() should be performed and eventually a sync().
:rtype: boolean | 10.009119 | 10.1129 | 0.989738 |
if self.lastforce is None:
self.lastforce = time.time()
return time.time() - self.lastforce >= self.forceipchangedetection_sleep | def needs_sync(self) | Check if enough time has elapsed to perform a sync().
A call to sync() should be performed every now and then, no matter what
has_state_changed() says. This is really just a safety thing to enforce
consistency in case the state gets messed up.
:rtype: boolean | 9.226229 | 9.54738 | 0.966362 |
if self.needs_check():
if self.has_state_changed():
LOG.debug("state changed, syncing...")
self.sync()
elif self.needs_sync():
LOG.debug("forcing sync after %s seconds",
self.forceipchangedetection_sleep)
... | def check(self) | Check if the detector changed and call sync() accordingly.
If the sleep time has elapsed, this method will see if the attached
detector has had a state change and call sync() accordingly. | 6.558125 | 5.663408 | 1.157982 |
import json
try:
return str(json.loads(text).get("ip"))
except ValueError as exc:
LOG.debug("Text '%s' could not be parsed", exc_info=exc)
return None | def _parser_jsonip(text) | Parse response text like the one returned by http://jsonip.com/. | 5.289304 | 4.63098 | 1.142157 |
if self.opts_url and self.opts_parser:
url = self.opts_url
parser = self.opts_parser
else:
url, parser = choice(self.urls) # noqa: S311
parser = globals().get("_parser_" + parser)
theip = _get_ip_from_url(url, parser)
if theip is None... | def detect(self) | Try to contact a remote webservice and parse the returned output.
Determine the IP address from the parsed output and return. | 6.494457 | 5.753747 | 1.128735 |
meth = getattr(plugin, call, None)
if meth is not None:
self.plugins.append((plugin, meth)) | def add_plugin(self, plugin, call) | Add plugin to list of plugins.
Will be added if it has the attribute I'm bound to. | 3.980527 | 3.691027 | 1.078434 |
final_result = None
for _, meth in self.plugins:
result = meth(*arg, **kw)
if final_result is None and result is not None:
final_result = result
return final_result | def listcall(self, *arg, **kw) | Call each plugin sequentially.
Return the first result that is not None. | 3.732605 | 2.946686 | 1.266713 |
# allow plugins loaded via entry points to override builtin plugins
new_name = self.plugin_name(plugin)
self._plugins[:] = [p for p in self._plugins
if self.plugin_name(p) != new_name]
self._plugins.append(plugin) | def add_plugin(self, plugin) | Add the given plugin. | 4.781631 | 4.614226 | 1.03628 |
for plug in self._plugins:
plug_name = self.plugin_name(plug)
plug.enabled = getattr(args, "plugin_%s" % plug_name, False)
if plug.enabled and getattr(plug, "configure", None):
if callable(getattr(plug, "configure", None)):
plug.co... | def configure(self, args) | Configure the set of plugins with the given args.
After configuration, disabled plugins are removed from the plugins list. | 2.955072 | 2.728997 | 1.082842 |
def get_help(plug):
import textwrap
if plug.__class__.__doc__:
# doc sections are often indented; compress the spaces
return textwrap.dedent(plug.__class__.__doc__)
return "(no help available)"
for plug in self._pl... | def options(self, parser, env) | Register commandline options with the given parser.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--with-$name option to be registered, be sure to call super().
:param parser: argparse parse... | 4.274117 | 4.251143 | 1.005404 |
from pkg_resources import iter_entry_points
seen = set()
for entry_point in self.entry_points:
for ep in iter_entry_points(entry_point):
if ep.name in seen:
continue
seen.add(ep.name)
try:
... | def load_plugins(self) | Load plugins from entry point(s). | 2.888811 | 2.67193 | 1.08117 |
from dyndnsc.plugins.builtin import PLUGINS
for plugin in PLUGINS:
self.add_plugin(plugin())
super(BuiltinPluginManager, self).load_plugins() | def load_plugins(self) | Load plugins from `dyndnsc.plugins.builtin`. | 5.803139 | 3.263933 | 1.777959 |
return self.handler.update_record(name=self._recordname,
address=ip) | def update(self, ip) | Update the IP on the remote service. | 14.269182 | 14.046649 | 1.015842 |
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile)
except TypeError:
# no config file (use environment variables)
pass
if self.config:
self.prefix = self.config.get('config_prefix', None)
... | def load(self) | (Re)Load config file. | 2.619957 | 2.571947 | 1.018667 |
# default is not a specified keyword argument so we can distinguish
# between a default set to None and no default sets
if not section and self.section:
section = self.section
default = kwargs.get('default', None)
env_var = "{}{}{}".format(
_suffi... | def get(self, var, section=None, **kwargs) | Retrieve a config var.
Return environment variable if it exists
(ie [self.prefix + _] + [section + _] + var)
otherwise var from config file.
If both are null and no default is set a ConfigError will be raised,
otherwise default will be returned.
:param var: key to look ... | 4.820043 | 4.560637 | 1.056879 |
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.keys() | def keys(self, section=None) | Provide dict like keys method | 3.542059 | 3.287073 | 1.077572 |
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.items() | def items(self, section=None) | Provide dict like items method | 3.591131 | 3.281394 | 1.094392 |
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.values() | def values(self, section=None) | Provide dict like values method | 3.623472 | 3.400551 | 1.065554 |
# pylint: disable=no-self-use
config_file = None
config_dir_env_var = self.env_prefix + '_DIR'
if not filename:
# Check env vars for config
filename = os.getenv(self.env_prefix, default=self.default_file)
# contains path so try directly
... | def _get_filepath(self, filename=None, config_dir=None) | Get config file.
:param filename: name of config file (not path)
:param config_dir: dir name prepended to file name.
Note: we use e.g. GBR_CONFIG_DIR here, this is the default
value in GBR but it is actually self.env_prefix + '_DIR' etc.
If config_dir is not supplied i... | 3.377065 | 3.23897 | 1.042636 |
timeout = 60
LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl)
params = {"domains": self.hostname.partition(".")[0], "token": self.__token}
if ip is None:
params["ip"] = ""
else:
params["ip"] = ip
# LOG... | def update(self, ip) | Update the IP on the remote service. | 4.555217 | 4.329501 | 1.052134 |
af_ok = (AF_INET, AF_INET6)
if family != AF_UNSPEC and family not in af_ok:
raise ValueError("Invalid family '%s'" % family)
ips = ()
try:
addrinfo = socket.getaddrinfo(hostname, None, family)
except socket.gaierror as exc:
# EAI_NODATA and EAI_NONAME are expected if thi... | def resolve(hostname, family=AF_UNSPEC) | Resolve hostname to one or more IP addresses through the operating system.
Resolution is carried out for the given address family. If no
address family is specified, only IPv4 and IPv6 addresses are returned. If
multiple IP addresses are found, all are returned.
:param family: AF_INET or AF_INET6 or A... | 2.702432 | 2.765415 | 0.977225 |
theip = next(iter(resolve(self.opts_hostname, self.opts_family)), None)
self.set_current_value(theip)
return theip | def detect(self) | Resolve the hostname to an IP address through the operating system.
Depending on the 'family' option, either ipv4 or ipv6 resolution is
carried out.
If multiple IP addresses are found, the first one is returned.
:return: ip address | 15.216112 | 10.83823 | 1.40393 |
for section in cfg.sections():
if section.startswith("preset:"):
out.write((section.replace("preset:", "")) + os.linesep)
for k, v in cfg.items(section):
out.write("\t%s = %s" % (k, v) + os.linesep) | def list_presets(cfg, out=sys.stdout) | Write a human readable list of available presets to out.
:param cfg: ConfigParser instance
:param out: file object to write to | 2.316498 | 2.595681 | 0.892443 |
parser = argparse.ArgumentParser()
arg_defaults = {
"daemon": False,
"loop": False,
"listpresets": False,
"config": None,
"debug": False,
"sleeptime": 300,
"version": False,
"verbose_count": 0
}
# add generic client options to the CLI... | def create_argparser() | Instantiate an `argparse.ArgumentParser`.
Adds all basic cli options including default values. | 2.197901 | 2.218111 | 0.990889 |
while True:
try:
# Do small sleeps in the main loop, needs_check() is cheap and does
# the rest.
time.sleep(15)
for dyndnsclient in dyndnsclients:
dyndnsclient.check()
except (KeyboardInterrupt,):
break
except (... | def run_forever(dyndnsclients) | Run an endless loop accross the give dynamic dns clients.
:param dyndnsclients: list of DynDnsClients | 5.979812 | 6.43598 | 0.929122 |
plugins = DefaultPluginManager()
plugins.load_plugins()
parser, _ = create_argparser()
# add the updater protocol options to the CLI:
for kls in updater_classes():
kls.register_arguments(parser)
for kls in detector_classes():
kls.register_arguments(parser)
# add the p... | def main() | Run the main CLI program.
Initializes the stack, parses command line arguments, and fires requested
logic. | 4.097314 | 4.091236 | 1.001486 |
if url and url.startswith('ssh://'):
# is there a user already ?
match = re.compile('ssh://([^@]+)@.+').match(url)
if match:
ssh_user = match.group(1)
if user and ssh_user != user:
# assume prevalence of argument
url = url.replace(... | def tidy_ssh_user(url=None, user=None) | make sure a git repo ssh:// url has a user set | 3.447794 | 3.343132 | 1.031306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.