text
stringlengths
81
112k
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 '/'). def get_build_file_path(self, build_module) -> str: """Return a full path to the build file of `build_module`. ...
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. def guess_uri_type(uri...
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...
Helper function to fetch a file from a URL. def fetch_url(url, dest, parent_to_remove_before_fetch): """Helper function to fetch a file from a URL.""" logger.debug('Downloading file {} from {}', dest, url) try: shutil.rmtree(parent_to_remove_before_fetch) except FileNotFoundError: pass ...
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...
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. def fetch_file_handler(unused_build_context, target, fetch, package_...
Return a target_name, script_name, package_tarball tuple for `target` def get_installer_desc(build_context, target) -> tuple: """Return a target_name, script_name, package_tarball tuple for `target`""" workspace_dir = build_context.get_workspace('CustomInstaller', target.name) target_name = split_name(targ...
Return set of target names that are contained within cached base images These targets may be considered "pre-built", and skipped during build. 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", a...
Write the `summary` JSON to `cache_dir`. Updated the accessed timestamp to now before writing. def write_summary(summary: dict, cache_dir: str): """Write the `summary` JSON to `cache_dir`. Updated the accessed timestamp to now before writing. """ # update the summary last-accessed timestamp s...
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. def load_target_from_cache(target: Target, build_context) -> ...
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. def copy_artifact(src_path: str, artifact_h...
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. def restore_artifact(src_path: str, artifact_hash: str, conf: Config): """Restore the artifact whose hash is `artifact_hash` to `src_path`. ...
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...
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. def get(self, key): """Return set of descendants of node named `key` in `target_graph`. Returns from cached dict if exis...
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`. 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...
Print a red `msg` to STDERR and exit. The message is formatted with `args` & `kwargs`. def fatal_noexc(msg, *args, **kwargs): """Print a red `msg` to STDERR and exit. The message is formatted with `args` & `kwargs`. """ print(Fore.RED + 'Fatal: ' + msg.format(*args, **kwargs) + Style.RESET_ALL, ...
Forcibly remove file or directory tree at `path`. Fail silently if base dir doesn't exist. def rmnode(path: str): """Forcibly remove file or directory tree at `path`. Fail silently if base dir doesn't exist.""" if isdir(path): rmtree(path) elif isfile(path): os.remove(path)
Sync source node (file / dir) to destination path using hard links. def link_node(abs_src: str, abs_dest: str, force: bool=False): """Sync source node (file / dir) to destination path using hard links.""" dest_parent_dir = split(abs_dest)[0] if not isdir(dest_parent_dir): # exist_ok=True in case of...
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...
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...
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...
Accumulate content of file at `filepath` in `hasher`. def acc_hash(filepath: str, hasher): """Accumulate content of file at `filepath` in `hasher`.""" with open(filepath, 'rb') as f: while True: chunk = f.read(_BUF_SIZE) if not chunk: break hasher.upd...
Return the hexdigest MD5 hash of content of file at `filepath`. def hash_file(filepath: str) -> str: """Return the hexdigest MD5 hash of content of file at `filepath`.""" md5 = hashlib.md5() acc_hash(filepath, md5) return md5.hexdigest()
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. def hash_tree(filepath: str) -> str: """Return the hexdigest MD5 hash of file ...
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). def add(self, artifact_type: ArtifactType, src_path: s...
Add all `src_paths` as artifact of type `artifact_type`. def extend(self, artifact_type: ArtifactType, src_paths: list): """Add all `src_paths` as artifact of type `artifact_type`.""" for src_path in src_paths: self.add(artifact_type, src_path, src_path)
Link all artifacts with types `types` under `base_dir` and return the number of linked artifacts. 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.""" num_link...
Link all artifacts required for a Docker image under `base_dir` and return the number of linked artifacts. 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.""" ...
Link all artifacts in `artifact_map` under `base_dir` and return the number of artifacts 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.""" num_linked = 0 ...
Read and return the content of the project README file. def get_readme(): """Read and return the content of the project README file.""" 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()
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...
Return a target extraction function for a specific builder and a specific build file. 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...
default rdopkg action runner including rdopkg action modules def rdopkg_runner(): """ default rdopkg action runner including rdopkg action modules """ aman = ActionManager() # assume all actions.* modules are action modules aman.add_actions_modules(actions) aman.fill_aliases() # additio...
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 def rdopkg(*cargs): """ rdopk...
Instantiate and return a complete and working dyndns client. :param config: a dictionary with configuration keys :param plugins: an object that implements PluginManager def getDynDnsClientForConfig(config, plugins=None): """Instantiate and return a complete and working dyndns client. :param config: a...
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. def sync(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...
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 def needs_check(self): """ Check if enough time has elapsed to perform a check(). ...
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 def needs_sync(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. def check(self): """ Check if the detector changed and call sync() accordingly. If the sl...
Parse response text like the one returned by http://jsonip.com/. def _parser_jsonip(text): """Parse response text like the one returned by http://jsonip.com/.""" import json try: return str(json.loads(text).get("ip")) except ValueError as exc: LOG.debug("Text '%s' could not be parsed", ...
Try to contact a remote webservice and parse the returned output. Determine the IP address from the parsed output and return. def detect(self): """ Try to contact a remote webservice and parse the returned output. Determine the IP address from the parsed output and return. """...
Add plugin to list of plugins. Will be added if it has the attribute I'm bound to. def add_plugin(self, plugin, call): """Add plugin to list of plugins. Will be added if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: ...
Call each plugin sequentially. Return the first result that is not None. def listcall(self, *arg, **kw): """Call each plugin sequentially. Return the first result that is not None. """ final_result = None for _, meth in self.plugins: result = meth(*arg, **k...
Add the given plugin. def add_plugin(self, plugin): """Add the given plugin.""" # 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_...
Configure the set of plugins with the given args. After configuration, disabled plugins are removed from the plugins list. def configure(self, args): """Configure the set of plugins with the given args. After configuration, disabled plugins are removed from the plugins list. """ ...
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...
Load plugins from entry point(s). def load_plugins(self): """Load plugins from entry point(s).""" 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: ...
Load plugins from `dyndnsc.plugins.builtin`. def load_plugins(self): """Load plugins from `dyndnsc.plugins.builtin`.""" from dyndnsc.plugins.builtin import PLUGINS for plugin in PLUGINS: self.add_plugin(plugin()) super(BuiltinPluginManager, self).load_plugins()
Update the IP on the remote service. def update(self, ip): """Update the IP on the remote service.""" return self.handler.update_record(name=self._recordname, address=ip)
(Re)Load config file. def load(self): """(Re)Load config file.""" 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: ...
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 ...
Provide dict like keys method def keys(self, section=None): """Provide dict like keys method""" if not section and self.section: section = self.section config = self.config.get(section, {}) if section else self.config return config.keys()
Provide dict like items method def items(self, section=None): """Provide dict like items method""" if not section and self.section: section = self.section config = self.config.get(section, {}) if section else self.config return config.items()
Provide dict like values method def values(self, section=None): """Provide dict like values method""" if not section and self.section: section = self.section config = self.config.get(section, {}) if section else self.config return config.values()
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...
Update the IP on the remote service. def update(self, ip): """Update the IP on the remote service.""" 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} ...
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...
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 def detect(self): """ Resolve the ho...
Write a human readable list of available presets to out. :param cfg: ConfigParser instance :param out: file object to write to 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 ...
Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values. def create_argparser(): """Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values. """ parser = argparse.ArgumentParser() arg_defaults = { "daemon": Fa...
Run an endless loop accross the give dynamic dns clients. :param dyndnsclients: list of DynDnsClients def run_forever(dyndnsclients): """ Run an endless loop accross the give dynamic dns clients. :param dyndnsclients: list of DynDnsClients """ while True: try: # Do small s...
Run the main CLI program. Initializes the stack, parses command line arguments, and fires requested logic. def main(): """ Run the main CLI program. Initializes the stack, parses command line arguments, and fires requested logic. """ plugins = DefaultPluginManager() plugins.load_p...
make sure a git repo ssh:// url has a user set def tidy_ssh_user(url=None, user=None): """make sure a git repo ssh:// url has a user set""" if url and url.startswith('ssh://'): # is there a user already ? match = re.compile('ssh://([^@]+)@.+').match(url) if match: ssh_user =...
Return a list of tuples, one per commit. Each tuple is (sha1, subject, bz_list). bz_list is a (possibly zero-length) list of numbers. def get_commit_bzs(self, from_revision, to_revision=None): """ Return a list of tuples, one per commit. Each tuple is (sha1, subject, bz_list). bz_list i...
Return the value of a git configuration option. This will return the value of the default parameter (which defaults to None) if the given option does not exist. def config_get(self, param, default=None): '''Return the value of a git configuration option. This will return the value of ...
Return an initialized ConfigParser. If no config filename is presented, `DEFAULT_USER_INI` is used if present. Also reads the built-in presets. :param config_file: string path def get_configuration(config_file=None): """Return an initialized ConfigParser. If no config filename is presented, `DEF...
Generate (client_name, client_cfg_dict) tuples from the configuration. Conflates the presets and removes traces of the preset configuration so that the returned dict can be used directly on a dyndnsc factory. :param cfg: ConfigParser def _iraw_client_configs(cfg): """ Generate (client_name, clien...
Construct configuration dictionary from configparser. Resolves presets and returns a dictionary containing: .. code-block:: bash { "client_name": { "detector": ("detector_name", detector_opts), "updater": [ ("updater_name", updater_opts)...
Detect and return the IP address. def detect(self): """Detect and return the IP address.""" if PY3: # py23 import subprocess # noqa: S404 @UnresolvedImport pylint: disable=import-error else: import commands as subprocess # @UnresolvedImport pylint: disable=import-erro...
Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, optional, default AF_INET (ipv4) :param flavour: selector for pub...
Detect the WAN IP of the current process through DNS. Depending on the 'family' option, either ipv4 or ipv6 resolution is carried out. :return: ip address def detect(self): """ Detect the WAN IP of the current process through DNS. Depending on the 'family' option, eit...
Set the detected IP in the current run (if any). def set_current_value(self, value): """Set the detected IP in the current run (if any).""" self._oldvalue = self.get_current_value() self._currentvalue = value if self._oldvalue != value: # self.notify_observers("new_ip_detect...
Parse all updater and detector related arguments from args. Returns a list of ("name", { "k": "v"}) :param args: argparse arguments def parse_cmdline_args(args, classes): """ Parse all updater and detector related arguments from args. Returns a list of ("name", { "k": "v"}) :param args: arg...
Register command line options. Implement this method for normal options behavior with protection from OptionConflictErrors. If you override this method and want the default --$name option(s) to be registered, be sure to call super(). def register_arguments(cls, parser): """Register com...
Tag the local_patches_branch with this package's NVR. def tag_patches_branch(package, local_patches_branch, patches_branch, force=False, push=False): """ Tag the local_patches_branch with this package's NVR. """ vr = specfile.Spec().get_vr(epoch=False) nvr_tag = package + '-' + vr ...
Return class object specified by module name and class name. Return None if module failed to be imported. :param module_name: string module name :param class_name: string class name def load_class(module_name, class_name): """Return class object specified by module name and class name. Return No...
Return class in ``classes`` identified by configuration key ``name``. def find_class(name, classes): """Return class in ``classes`` identified by configuration key ``name``.""" name = name.lower() cls = next((c for c in classes if c.configuration_key == name), None) if cls is None: raise ValueE...
Convert to snakecase removing non alpha numerics Word #word -> word_word. def alphasnake(string): """Convert to snakecase removing non alpha numerics Word #word -> word_word. """ if string: string = " ".join( [re.sub(r'\W+', '', word) for word in string.split()] ) ...
Split CamelCased words. CamelCase -> Camel Case, dromedaryCase -> dromedary Case. def decamel(string): """"Split CamelCased words. CamelCase -> Camel Case, dromedaryCase -> dromedary Case. """ regex = re.compile(r'(\B[A-Z][a-z]*)') return regex.sub(r' \1', string)
Convert to lower case, join camel case with underscore. CamelCase -> camel_case. Camel Case -> camel_case. def decamel_to_snake(string): """Convert to lower case, join camel case with underscore. CamelCase -> camel_case. Camel Case -> camel_case. """ strings = [decamel(word) if not word.isupper() e...
Return default distroinfo info file def info_file(distro=None): """Return default distroinfo info file""" if not distro: distro = cfg['DISTRO'] info_file_conf = distro.upper() + 'INFO_FILE' try: return cfg[info_file_conf] except KeyError: raise exception.InvalidUsage( ...
Get DistroInfo initialized from configuration def get_distroinfo(distro=None): """Get DistroInfo initialized from configuration""" if not distro: distro = cfg['DISTRO'] _info_file = info_file(distro) # prefer git fetcher if available git_info_url_conf = distro.upper() + 'INFO_REPO' try:...
Received a standard style rpm fullname and returns name, version, release, epoch, arch Example: foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386 1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64 This function replaces rpmUtils.miscutils.splitFilename, see https://bugzilla.redhat.com/1452801 ...
Return a tuple of (epoch, version, release) from a version string This function replaces rpmUtils.miscutils.stringToVersion, see https://bugzilla.redhat.com/1364504 def string_to_version(verstring): """ Return a tuple of (epoch, version, release) from a version string This function replaces rpmUt...
Return the filename for a .spec file in this directory. def spec_fn(spec_dir='.'): """ Return the filename for a .spec file in this directory. """ specs = [f for f in os.listdir(spec_dir) if os.path.isfile(f) and f.endswith('.spec')] if not specs: raise exception.SpecFileNotFou...
Split a version string into numeric X.Y.Z part and the rest (milestone). def version_parts(version): """ Split a version string into numeric X.Y.Z part and the rest (milestone). """ m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version) if m: numver = m.group(1) rest = m.group(2) + m...
Split RPM Release string into (numeric X.Y.Z part, milestone, rest). :returns: a three-element tuple (number, milestone, rest). If we cannot determine the "milestone" or "rest", those will be an empty string. def release_parts(version): """ Split RPM Release string into (numeri...
Return a value of # name=value comment in spec or None. def get_magic_comment(self, name, expand_macros=False): """Return a value of # name=value comment in spec or None.""" match = re.search(r'^#\s*?%s\s?=\s?(\S+)' % re.escape(name), self.txt, flags=re.M) if not match...
Return a tuple (version, number_of_commits) that are parsed from the patches_base in the specfile. def get_patches_base(self, expand_macros=False): """Return a tuple (version, number_of_commits) that are parsed from the patches_base in the specfile. """ match = re.search(r'(?<=p...
Returns a string representing a regex for filtering out patches This string is parsed from a comment in the specfile that contains the word filter-out followed by an equal sign. For example, a comment as such: # patches_ignore=(regex) would mean this method returns the str...
Check if this Release value is something we can parse. :rtype: bool def recognized_release(self): """ Check if this Release value is something we can parse. :rtype: bool """ _, _, rest = self.get_release_parts() # If "rest" is not a well-known value here, then th...
get VR string from .spec Version, Release and Epoch epoch is None: prefix epoch if present (default) epoch is True: prefix epoch even if not present (0:) epoch is False: omit epoch even if present def get_vr(self, epoch=None): """get VR string from .spec Version, Release and Epoch ...
get NVR string from .spec Name, Version, Release and Epoch def get_nvr(self, epoch=None): """get NVR string from .spec Name, Version, Release and Epoch""" name = self.get_tag('Name', expand_macros=True) vr = self.get_vr(epoch=epoch) return '%s-%s' % (name, vr)
Write the textual content (self._txt) to .spec file (self.fn). def save(self): """ Write the textual content (self._txt) to .spec file (self.fn). """ if not self.txt: # no changes return if not self.fn: raise exception.InvalidAction( "Can't sa...
Detect IP address. kind can be: IPV4 - returns IPv4 address IPV6_ANY - returns any IPv6 address (no preference) IPV6_PUBLIC - returns public IPv6 address IPV6_TMP - returns temporary IPV6 address (privacy extensions) This function either returns an IP address (str) or raise...
Setup koji client session def setup_kojiclient(profile): """Setup koji client session """ opts = koji.read_config(profile) for k, v in opts.iteritems(): opts[k] = os.path.expanduser(v) if type(v) is str else v kojiclient = koji.ClientSession(opts['server'], opts=opts) kojiclient.ssl_log...
Retrieve sources using spectool def retrieve_sources(): """Retrieve sources using spectool """ spectool = find_executable('spectool') if not spectool: log.warn('spectool is not installed') return try: specfile = spec_fn() except Exception: return cmd = [spec...
Create an srpm Requires that sources are available in local directory dist: set package dist tag (default: el7) def create_srpm(dist='el7'): """Create an srpm Requires that sources are available in local directory dist: set package dist tag (default: el7) """ if not RPM_AVAILABLE: ...
Compute the authentication key for freedns.afraid.org. This is the SHA1 hash of the string b'userid|password'. :param userid: ascii username :param password: ascii password :return: ascii authentication key (SHA1 at this point) def compute_auth_key(userid, password): """ Compute the authentic...