text
stringlengths
81
112k
Get attribute value or return default Whole data dictionary is returned when no attribute provided. Supports direct values retrieval from deep dictionaries as well. Dictionary path should be provided as list. The following two examples are equal: tree.data['hardware']['memory']...
Create or update child with given data def child(self, name, data, source=None): """ Create or update child with given data """ try: if isinstance(data, dict): self.children[name].update(data) else: self.children[name].grow(data) except Ke...
Grow the metadata tree for the given directory path Note: For each path, grow() should be run only once. Growing the tree from the same path multiple times with attribute adding using the "+" sign leads to adding the value more than once! def grow(self, path): """ Grow the meta...
Climb through the tree (iterate leaf/all nodes) def climb(self, whole=False): """ Climb through the tree (iterate leaf/all nodes) """ if whole or not self.children: yield self for name, child in self.children.items(): for node in child.climb(whole): yield...
Find node with given name def find(self, name): """ Find node with given name """ for node in self.climb(whole=True): if node.name == name: return node return None
Filter tree nodes based on given criteria def prune(self, whole=False, keys=[], names=[], filters=[]): """ Filter tree nodes based on given criteria """ for node in self.climb(whole): # Select only nodes with key content if not all([key in node.data for key in keys]): ...
Show metadata def show(self, brief=False, formatting=None, values=[]): """ Show metadata """ # Show nothing if there's nothing if not self.data: return None # Custom formatting if formatting is not None: formatting = re.sub("\\\\n", "\n", formatting) ...
Creates labels which represent the tree level of each node when generating option labels. def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ level = getattr(obj, obj._mptt_meta.level_attr)...
Attempts to move the node using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidNode`` to redisplay the form with t...
Iterating a set of dirs under the static root, this method tries to find a file named like one of the names and file ext passed, and returns the storage path to the first file it encounters. Usage this method makes it possible to override static files (such as icon sets) in a s...
Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.png" def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext=...
Added 'filtered' param, so the template's js knows whether the results have been affected by a GET param or not. Only when the results are not filtered you can drag and sort the tree def result_tree_flat(context, cl, request): """ Added 'filtered' param, so the template's js knows whether the results h...
Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `path` argument in the URLconf, but subclasses can override this to return any object. def get_object(self, queryset=None): """ Returns the object the view is displaying. By defau...
Instantiates and returns the view class that will generate the actual context for this plugin. def get_detail_view(self, request, object, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. """ view = self.get_vi...
Instantiates and returns the view class that will generate the actual context for this plugin. ``queryset`` can be an actual QuerySet or any iterable. def get_listing_view(self, request, queryset, opts=None): """ Instantiates and returns the view class that will generate the ac...
Instantiates and returns the view class that will generate the actual context for this plugin. def get_view(self, request, view_class, opts=None): """ Instantiates and returns the view class that will generate the actual context for this plugin. """ kwargs = {} i...
Formating options def options_formatting(self): """ Formating options """ group = self.parser.add_argument_group("Format") group.add_argument( "--format", dest="formatting", default=None, help="Custom output format using the {} expansion") group.add_argument( ...
Utilities def options_utils(self): """ Utilities """ group = self.parser.add_argument_group("Utils") group.add_argument( "--path", action="append", dest="paths", help="Path to the metadata tree (default: current directory)") group.add_argument( "--ver...
List names def command_ls(self): """ List names """ self.parser = argparse.ArgumentParser( description="List names of available objects") self.options_select() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) self.show(brief=True...
Show metadata def command_show(self): """ Show metadata """ self.parser = argparse.ArgumentParser( description="Show metadata of available objects") self.options_select() self.options_formatting() self.options_utils() self.options = self.parser.parse_args(sel...
Initialize tree def command_init(self): """ Initialize tree """ self.parser = argparse.ArgumentParser( description="Initialize a new metadata tree") self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) # For each path create an .fmf director...
Show metadata for each path given def show(self, brief=False): """ Show metadata for each path given """ output = [] for path in self.options.paths or ["."]: if self.options.verbose: utils.info("Checking {0} for metadata.".format(path)) tree = fmf.Tree(pa...
Return true if provided filter matches given dictionary of values Filter supports disjunctive normal form with '|' used for OR, '&' for AND and '-' for negation. Individual values are prefixed with 'value:', leading/trailing white-space is stripped. For example:: tag: Tier1 | tag: Tier2 | tag: Tie...
Return text in desired color if coloring enabled Available colors: black red green yellow blue magenta cyan white. Alternatively color can be prefixed with "light", e.g. lightgreen. def color(text, color=None, background=None, light=False, enabled="auto"): """ Return text in desired color if coloring ...
Create fmf logger def _create_logger(name='fmf', level=None): """ Create fmf logger """ # Create logger, handler and formatter logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) ...
Works just like the default Manager's :func:`filter` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to retrieve, e.g. ``"path/to/folder"``. def filter(self, *args, **kwargs): """ ...
Works just like the default Manager's :func:`exclude` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to exclude, e.g. ``"path/to/folder"``. def exclude(self, *args, **kwargs): """ ...
Works just like the default Manager's :func:`get` method, but you can pass an additional keyword argument named ``path`` specifying the full path of the object you want to retrieve, e.g. ``"path/to/folder/readme.txt"``. def get(self, *args, **kwargs): """ Works just like the def...
Validates value and throws ValidationError. Subclasses should override this to provide validation logic. def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not sel...
Returns a fully qualified URL for the :attr:`file` field, including protocol, domain and port. In most cases, you can just use ``file.url`` instead, which (depending on your ``MEDIA_URL``) may or may not contain the domain. In some cases however, you always need a fully qualified URL. Th...
Returns the URL for viewing a FileNode in the admin. def get_admin_url(self, query_params=None, use_path=False): """Returns the URL for viewing a FileNode in the admin.""" if not query_params: query_params = {} url = '' if self.is_top_node(): url = reverse('adm...
Returns object metadata that has been selected to be displayed to users, compiled as a string. def get_metadata_display(self, field_formats = {}, escape=True): """Returns object metadata that has been selected to be displayed to users, compiled as a string. """ def field_format(...
Returns object metadata that has been selected to be displayed to users, compiled as a string including default formatting, for example bold titles. You can use this method in templates where you want to output image captions. def get_caption_formatted(self, field_formats = app_setting...
Returns object metadata suitable for use as the HTML ``alt`` attribute. You can use this method in templates:: <img src="{{ node.file.url }}" alt="{{ node.alt }}" /> def alt(self): """Returns object metadata suitable for use as the HTML ``alt`` attribute. You can use this method in...
Attempts to move the nodes using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidMove`` to redisplay the form with ...
Deletes the selected files from storage def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: stor...
Almost the same as :func:`get_nested_filenode_list`, but returns a flat (one-dimensional) list. Using the same QuerySet as in the example for `get_nested_filenode_list`, this method would return:: [ <FileNode: Empty folder>, <FileNode: Photo folder>, <FileNode: photo1.jp...
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''): """ Returns a formatted HTML link tag to the Fi...
Deletes multiple instances and makes sure the MPTT fields get recalculated properly. (Because merely doing a bulk delete doesn't trigger the post_delete hooks.) def delete_selected_tree(self, modeladmin, request, queryset): """ Deletes multiple instances and makes sure the MPTT fields get recal...
Return a normalized canonical target name for the `target_name` observed in build module `build_module`. A normalized canonical target name is of the form "<build module>:<name>", where <build module> is the relative normalized path from the project root to the target build module (POSIX), and <name...
Return a normalized target name (where `**:*` is the normalized form of itself). Target specifier can be: - `**:*` - means to recursively build all targets under current working dir. - relative path from current working directory to another directory - means to build all targets defin...
Return sorted hashes of `targets`. def hashify_targets(targets: list, build_context) -> list: """Return sorted hashes of `targets`.""" return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
Return mapping from file path to file hash. def hashify_files(files: list) -> dict: """Return mapping from file path to file hash.""" return {filepath.replace('\\', '/'): hash_tree(filepath) for filepath in listify(files)}
Return a cachable representation of the prop `value` given its type. def process_prop(prop_type: PT, value, build_context): """Return a cachable representation of the prop `value` given its type.""" if prop_type in (PT.Target, PT.TargetList): return hashify_targets(value, build_context) elif prop_t...
Compute and store a JSON serialization of this target for caching purposes. The serialization includes: - The build flavor - The builder name - Target tags - Hashes of target dependencies & buildenv - Processed props (where target props are replaced with their...
Return JSON serialization of this target for caching purposes. def json(self, build_context) -> str: """Return JSON serialization of this target for caching purposes.""" if self._json is None: self.compute_json(build_context) return self._json
Compute and store the hash of this target for caching purposes. The hash is computed over the target JSON representation. def compute_hash(self, build_context): """Compute and store the hash of this target for caching purposes. The hash is computed over the target JSON representation. ...
Return the hash of this target for caching purposes. def hash(self, build_context) -> str: """Return the hash of this target for caching purposes.""" if self._hash is None: self.compute_hash(build_context) return self._hash
Handle Docker image build cache. Return image ID if image is cached, and there's no need to redo the build. Return None if need to build the image (whether cached locally or not). Raise RuntimeError if not allowed to build the image because of state of local cache. TODO(itamar): figure out a bette...
Build Docker image, and return a (image_id, image_name:tag) tuple of built image, if built successfully. Notes: Using the given image name & tag as they are, but using the global host Docker image namespace (as opposed to a private-project-workspace), so collisions between projects are possible ...
Add a brace-handler stream-handler using `stream` to `logger`. def add_stream_handler(logger, stream): """Add a brace-handler stream-handler using `stream` to `logger`.""" handler = logging.StreamHandler(stream=stream) # Using Brace Formatter (see # https://docs.python.org/3.5/howto/logging-cookbook.ht...
Initialize and configure logging. def configure_logging(conf): """Initialize and configure logging.""" root_logger = logging.getLogger() root_logger.setLevel(getattr(logging, conf.loglevel.upper())) if conf.logtostderr: add_stream_handler(root_logger, sys.stderr) if conf.logtostdout: ...
Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' wi...
Register a builder signature & docstring for `builder_name`. The input for the builder signature is a list of "sig-spec"s representing the builder function arguments. Each sig-spec in the list can be: 1. A string. This represents a simple untyped positional argument name, w...
Remove a registered builder `builder_name`. No reason to use this except for tests. def remove_builder(cls, builder_name: str): """Remove a registered builder `builder_name`. No reason to use this except for tests. """ cls.builders.pop(builder_name, None) for hook_spec...
Return a normalized build module name for `build_file_path`. def to_build_module(build_file_path: str, conf: Config) -> str: """Return a normalized build module name for `build_file_path`.""" build_file = Path(build_file_path) root = Path(conf.project_root) return build_file.resolve().relative_to(root)...
Print out version information about YABT and detected builders. def cmd_version(unused_conf): """Print out version information about YABT and detected builders.""" import pkg_resources print('This is {} version {}, imported from {}' .format(__oneliner__, __version__, __file__)) if len(Plugin....
Print out information on loaded builders and hooks. def cmd_list(unused_conf: Config): """Print out information on loaded builders and hooks.""" for name, builder in sorted(Plugin.builders.items()): if builder.func: print('+- {0:16s} implemented in {1.__module__}.{1.__name__}()' ...
Build requested targets, and their dependencies. def cmd_build(conf: Config, run_tests: bool=False): """Build requested targets, and their dependencies.""" build_context = BuildContext(conf) populate_targets_graph(build_context, conf) build_context.build_graph(run_tests=run_tests) build_context.wri...
Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: > ybt dot :foo :bar | dot -Tpng -o graph.png def cmd_dot(conf: Config): """Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: ...
Print out a neat targets dependency tree based on requested targets. def cmd_tree(conf: Config): """Print out a neat targets dependency tree based on requested targets.""" build_context = BuildContext(conf) populate_targets_graph(build_context, conf) def print_target_with_deps(target, depth=2): ...
Main `ybt` console script entry point - run YABT from command-line. def main(): """Main `ybt` console script entry point - run YABT from command-line.""" conf = init_and_get_conf() logger = make_logger(__name__) logger.info('YaBT version {}', __version__) handlers = { 'build': YabtCommand(f...
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. def cpp_app_builder(build_context, target): """Pack a C++ binary as a Docker image with its runtim...
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. def make_pre_build_hook(extra_compiler_config_params): """Return a pre-build hook fu...
Compile list of C++ source files in a buildenv image and return list of generated object file. 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 gener...
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...
Return list of source files for `target`. def get_source_files(target, build_context) -> list: """Return list of source files for `target`.""" all_sources = list(target.props.sources) for proto_dep_name in target.props.protos: proto_dep = build_context.targets[proto_dep_name] all_sources.ex...
Compile and link a C++ binary for `target`. def build_cpp(build_context, target, compiler_config, workspace_dir): """Compile and link a C++ binary for `target`.""" rmtree(workspace_dir) binary = join(*split(target.name)) objects = link_cpp_artifacts(build_context, target, workspace_dir, True) build...
Build a C++ binary executable def cpp_prog_builder(build_context, target): """Build a C++ binary executable""" 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)
Build C++ object files def cpp_lib_builder(build_context, target): """Build C++ object files""" 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...
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...
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...
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...
Return the argument parser. :param project_config_file: Absolute path to project-specific config file. If cached parser already exists - return it immediately. Otherwise, initialize a new `ConfigArgParser` that is able to take default values from a hierarchy of config files and environment variables, ...
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 ...
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...
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. def call_user_func(settings_module, func_name, *args, **kwargs): """Cal...
Update the flavor arg based on the settings API def get_build_flavor(settings_module, args): """Update the flavor arg based on the settings API""" known_flavors = listify(call_user_func(settings_module, 'known_flavors')) if args.flavor: if args.flavor not in known_flavors: raise ValueEr...
Initialize a YABT CLI environment and return a Config instance. :param argv: Manual override of command-line params to parse (for tests). 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 param...
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 ...
Raise error about unresolved targets during graph parsing. def raise_unresolved_targets(build_context, conf, unknown_seeds, seed_refs): """Raise error about unresolved targets during graph parsing.""" def format_target(target_name): # TODO: suggest similar known target names build_module = spl...
Return a decorator for registering a SCM provider named `scm_name`. def register_scm_provider(scm_name: str): """Return a decorator for registering a SCM provider named `scm_name`.""" def register_decorator(scm_class: SourceControl): """Decorator for registering SCM provider.""" if scm_name in...
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. def get_provider(cls, scm_name: str, conf) -> SourceControl: """Loa...
Write build graph in dot format to `out_f` file-like object. def write_dot(build_context, conf: Config, out_f): """Write build graph in dot format to `out_f` file-like object.""" not_buildenv_targets = get_not_buildenv_targets(build_context) prebuilt_targets = get_prebuilt_targets(build_context) out_f....
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...
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. 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 mis...
Generate all dependencies of `target` by topological sort order. def walk_target_deps_topological_order(self, target: Target): """Generate all dependencies of `target` by topological sort order.""" all_deps = get_descendants(self.target_graph, target.name) for dep_name in topological_sort(self....
Generate only direct dependencies of `target`. def generate_direct_deps(self, target: Target): """Generate only direct dependencies of `target`.""" yield from (self.targets[dep_name] for dep_name in sorted(target.deps))
Generate names of all dependencies (descendants) of `target`. def generate_dep_names(self, target: Target): """Generate names of all dependencies (descendants) of `target`.""" yield from sorted(get_descendants(self.target_graph, target.name))
Generate all dependencies of `target` (the target nodes). def generate_all_deps(self, target: Target): """Generate all dependencies of `target` (the target nodes).""" yield from (self.targets[dep_name] for dep_name in self.generate_dep_names(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). def register_target(self, target: Target): ...
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. ...
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. def get_target_extraction_context(self, build_file_path: str) -> dict: """Return a build f...
Return a graph induced by buildenv nodes def get_buildenv_graph(self): """Return a graph induced by buildenv nodes""" # 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 ...
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...
Run a command in a named BuildEnv Docker image. :param buildenv_target_name: A named Docker image target in which the command should be run. :param cmd: The command to run, as you'd pass to subprocess.run() :param cmd_env: A dictionary of environment variabl...
Invoke the builder function for a target. def build_target(self, target: Target): """Invoke the builder function for a target.""" builder = Plugin.builders[target.builder_name] if builder.func: logger.debug('About to invoke the {} builder function for {}', t...
Register the artifact metadata dictionary for a built target. def register_target_artifact_metadata(self, target: str, metadata: dict): """Register the artifact metadata dictionary for a built target.""" with self.context_lock: self.artifacts_metadata[target.name] = metadata
Write out a JSON file with all built targets artifact metadata, if such output file is specified. def write_artifacts_metadata(self): """Write out a JSON file with all built targets artifact metadata, if such output file is specified.""" if self.conf.artifacts_metadata_file: ...
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). def can_use_cache(self, target: Target) -> bool: """Return True if should attempt to load `target` fr...