text
stringlengths
18
773k
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 supe...
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: continue ...
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()
def update(self, ip): """Update the IP on the remote service.""" return self.handler.update_record(name=self._recordname, address=ip)
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: self.prefix ...
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 defa...
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()
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()
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()
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 ac...
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} if ip is None: params["ip"...
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 r...
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 """ ...
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 """ for section in cfg.sections(): if section.startswith("preset:"): out.write((section.replace("preset:", "")...
def create_argparser(): """Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values. """ parser = argparse.ArgumentParser() arg_defaults = { "daemon": False, "loop": False, "listpresets": False, "config": None, "debug": Fa...
def run_forever(dyndnsclients): """ Run an endless loop accross the give dynamic dns clients. :param dyndnsclients: list of DynDnsClients """ while True: try: # Do small sleeps in the main loop, needs_check() is cheap and does # the rest. time.sleep(15) ...
def main(): """ Run the main CLI program. Initializes the stack, parses command line arguments, and fires requested logic. """ plugins = DefaultPluginManager() plugins.load_plugins() parser, _ = create_argparser() # add the updater protocol options to the CLI: for kls in update...
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 = match.group(1) if user and ssh_user...
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 is a (possibly zero-length) list of numbers. """ rng = self.rev_range(from_revision, to_revision) GIT_COMMIT_FIELDS = ['...
def config_get(self, param, default=None): '''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.''' try: return self("config", "--get", param, ...
def get_configuration(config_file=None): """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 """ parser = configparser.ConfigParser() if config_file is None: ...
def _iraw_client_configs(cfg): """ 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 """ client_names = cf...
def collect_config(cfg): """ Construct configuration dictionary from configparser. Resolves presets and returns a dictionary containing: .. code-block:: bash { "client_name": { "detector": ("detector_name", detector_opts), "updater": [ ...
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-error try: theip = ...
def find_ip(family=AF_INET, flavour="opendns"): """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, defa...
def detect(self): """ 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 """ theip = find_ip(family=self.opts_family) self.set_current_value(theip) ...
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_detected", {"ip": value}) LOG.debug("%s.set_...
def parse_cmdline_args(args, classes): """ Parse all updater and detector related arguments from args. Returns a list of ("name", { "k": "v"}) :param args: argparse arguments """ if args is None: raise ValueError("args must not be None") parsed_args = {} for kls in classes: ...
def register_arguments(cls, parser): """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 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 tag_cmd = ['tag', nvr_tag, local_patches_branch] ...
def load_class(module_name, class_name): """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 """ try: plugmod = import_module(module_name) except Exc...
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 ValueError("No class named '%s' could be found" % name) return cls
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()] ) string = decamel_to_snake(string) return string
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)
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() else word.lower() for word in string.split()] return "_".join([snake(dstring)for dstring in st...
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( why="Couldn't find config optio...
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: remote_git_info = cfg[git_info_url_con...
def split_filename(filename): """ 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, se...
def string_to_version(verstring): """ Return a tuple of (epoch, version, release) from a version string This function replaces rpmUtils.miscutils.stringToVersion, see https://bugzilla.redhat.com/1364504 """ # is there an epoch? components = verstring.split(':') if len(components) > 1: ...
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.SpecFileNotFound() if len(specs) != 1: raise exception.Mult...
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.group(3) return numver, rest else: return version, ''
def release_parts(version): """ 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. """ numver, tail = version_par...
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 None val = match.group(1) ...
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'(?<=patches_base=)[\w.+?%{}]+', self.txt) if not match: return None, 0 patches_base ...
def get_patches_ignore_regex(self): """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) ...
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 this package is # using a Release value pattern we cannot recognize. ...
def get_vr(self, epoch=None): """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 """ version = self.get_tag('Version', exp...
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)
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 save .spec file without its file name specified.") f = cod...
def detect_ip(kind): """ 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...
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_login(opts['cert'], None, opts...
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 = [spectool, "-g", specfile] output ...
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: raise RpmModuleNotAvailable() path = os.getcwd() try: specfile = spec_fn() spec = Spec(specfile) ...
def compute_auth_key(userid, password): """ 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) """ import sys...
def records(credentials, url="https://freedns.afraid.org/api/"): """ Yield the dynamic DNS records associated with this account. :param credentials: an AfraidCredentials instance :param url: the service URL """ params = {"action": "getdyndns", "sha": credentials.sha} req = requests.get( ...
def update(url): """ Update remote DNS record by requesting its special endpoint URL. This automatically picks the IP address using the HTTP connection: it is not possible to specify the IP address explicitly. :param url: URL to retrieve for triggering the update :return: IP address """ ...
def sha(self): """Return sha, lazily compute if not done yet.""" if self._sha is None: self._sha = compute_auth_key(self.userid, self.password) return self._sha
def update(self, *args, **kwargs): """Update the IP on the remote service.""" # first find the update_url for the provided account + hostname: update_url = next((r.update_url for r in records(self._credentials, self._url) if r.hostname == sel...
def register_observer(self, observer, events=None): """Register a listener function. :param observer: external listener function :param events: tuple or list of relevant events (default=None) """ if events is not None and not isinstance(events, (tuple, list)): events...
def notify_observers(self, event=None, msg=None): """Notify observers.""" for observer, events in list(self._observers.items()): # LOG.debug("trying to notify the observer") if events is None or event is None or event in events: try: observer(s...
def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: kind = IPV6_PUBLIC else: # 'INET': kind = IPV4 theip = None try: theip = detect_ip(kind) except GetIpException: LOG.exception("socket detector ...
def _detect(self): """Use the netifaces module to detect ifconfig information.""" theip = None try: if self.opts_family == AF_INET6: addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6] else: addrlist = netifaces.ifaddresse...
def clean_tempdir(context, scenario): """ Clean up temporary test dirs for passed tests. Leave failed test dirs for manual inspection. """ tempdir = getattr(context, 'tempdir', None) if tempdir and scenario.status == 'passed': shutil.rmtree(tempdir) del(context.tempdir)
def is_reserved_ip(self, ip): """Check if the given ip address is in a reserved ipv4 address space. :param ip: ip address :return: boolean """ theip = ipaddress(ip) for res in self._reserved_netmasks: if theip in ipnetwork(res): return True ...
def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip() return randomip
def detect(self): """Detect IP and return it.""" for theip in self.rips: LOG.debug("detected %s", str(theip)) self.set_current_value(str(theip)) return str(theip)
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 = {"myip": ip, "hostname": self.hostname} req = requests.get(self._updateurl, params=params, headers=constan...
def patches_base_ref(default=exception.CantGuess): """Return a git reference to patches branch base. Returns first part of .spec's patches_base is found, otherwise return Version(+%{milestone}). """ ref = None try: spec = specfile.Spec() ref, _ = spec.get_patches_base(expand_mac...
def display_listitems(items, url): '''Displays a list of items along with the index to enable a user to select an item. ''' if (len(items) == 2 and items[0].get_label() == '..' and items[1].get_played()): display_video(items) else: label_width = get_max_len(item.get_label() f...
def display_video(items): '''Prints a message for a playing video and displays the parent listitem. ''' parent_item, played_item = items title_line = 'Playing Media %s (%s)' % (played_item.get_label(), played_item.get_path()) parent_line = '[0] %s (%s...
def get_user_choice(items): '''Returns the selected item from provided items or None if 'q' was entered for quit. ''' choice = raw_input('Choose an item or "q" to quit: ') while choice != 'q': try: item = items[int(choice)] print # Blank line for readability between ...
def decode(data): """ Decode data employing some charset detection and including unicode BOM stripping. """ if isinstance(data, unicode): return data # Detect standard unicode BOMs. for bom, encoding in UNICODE_BOMS: if data.startswith(bom): return data[len(bom)...
def get_context(self, line=1, column=0): 'Returns a tuple containing the context for a line' line -= 1 # The line is one-based # If there is no data in the file, there can be no context. datalen = len(self.data) if datalen <= line: return None build = [sel...
def _format_line(self, data, column=0, rel_line=1): 'Formats a line from the data to be the appropriate length' line_length = len(data) if line_length > 140: if rel_line == 0: # Trim from the beginning data = '... %s' % data[-140:] elif re...
def get_line(self, position): 'Returns the line number that the given string position is found on' datalen = len(self.data) count = len(self.data[0]) line = 1 while count < position: if line >= datalen: break count += len(self.data[line]) ...
def load_addon_strings(addon, filename): '''This is not an official XBMC method, it is here to faciliate mocking up the other methods when running outside of XBMC.''' def get_strings(fn): xml = parse(fn) strings = dict((tag.getAttribute('id'), tag.firstChild.data) for tag in xml.getElementsB...
def get_addon_id(addonxml): '''Parses an addon id from the given addon.xml filename.''' xml = parse(addonxml) addon_node = xml.getElementsByTagName('addon')[0] return addon_node.getAttribute('id')
def get_addon_name(addonxml): '''Parses an addon name from the given addon.xml filename.''' xml = parse(addonxml) addon_node = xml.getElementsByTagName('addon')[0] return addon_node.getAttribute('name')
def _create_dir(path): '''Creates necessary directories for the given path or does nothing if the directories already exist. ''' try: os.makedirs(path) except OSError, exc: if exc.errno == errno.EEXIST: pass else: raise
def translatePath(path): '''Creates folders in the OS's temp directory. Doesn't touch any possible XBMC installation on the machine. Attempting to do as little work as possible to enable this function to work seamlessly. ''' valid_dirs = ['xbmc', 'home', 'temp', 'masterprofile', 'profile', '...
def _parse_request(self, url=None, handle=None): '''Handles setup of the plugin state, including request arguments, handle, mode. This method never needs to be called directly. For testing, see plugin.test() ''' # To accomdate self.redirect, we need to be able to parse a...
def register_module(self, module, url_prefix): '''Registers a module with a plugin. Requires a url_prefix that will then enable calls to url_for. :param module: Should be an instance `xbmcswift2.Module`. :param url_prefix: A url prefix to use for all module urls, ...
def cached_route(self, url_rule, name=None, options=None, TTL=None): '''A decorator to add a route to a view and also apply caching. The url_rule, name and options arguments are the same arguments for the route function. The TTL argument if given will passed along to the caching decorato...
def route(self, url_rule, name=None, options=None): '''A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view.''' # TODO: change options kwarg to defaults def decorator(f): view_name = name or f.__name__ ...
def add_url_rule(self, url_rule, view_func, name, options=None): '''This method adds a URL rule for routing purposes. The provided name can be different from the view function name if desired. The provided name is what is used in url_for to build a URL. The route decorator provi...
def url_for(self, endpoint, **items): '''Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator. Raises AmbiguousUrlException if there is more t...
def redirect(self, url): '''Used when you need to redirect to another view, and you only have the final plugin:// url.''' # TODO: Should we be overriding self.request with the new request? new_request = self._parse_request(url=url, handle=self.request.handle) log.debug('Redirecti...
def run(self, test=False): '''The main entry point for a plugin.''' self._request = self._parse_request() log.debug('Handling incoming request for %s', self.request.path) items = self._dispatch(self.request.path) # Close any open storages which will persist them to disk ...
def main(): '''The entry point for the console script xbmcswift2. The 'xbcmswift2' script is command bassed, so the second argument is always the command to execute. Each command has its own parser options and usages. If no command is provided or the -h flag is used without any other commands, the ...
def colorize_text(self, text): """Adds escape sequences to colorize text and make it beautiful. To colorize text, prefix the text you want to color with the color (capitalized) wrapped in double angle brackets (i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you don't, it w...
def write(self, text): 'Uses curses to print in the fanciest way possible.' # Add color to the terminal. if not self.no_color: text = self.colorize_text(text) else: pattern = re.compile('\<\<[A-Z]*?\>\>') text = pattern.sub('', text) text += ...
def say(self, input=None, **kwargs): """Talk to Cleverbot. Arguments: input: The input argument is what you want to say to Cleverbot, such as "hello". tweak1-3: Changes Cleverbot's mood. **kwargs: Keyword arguments to update the request parameters wit...
def live_pidfile(pidfile): # pragma: no cover """(pidfile:str) -> int | None Returns an int found in the named file, if there is one, and if there is a running process with that process id. Return None if no such process exists. """ pid = read_pidfile(pidfile) if pid: try: ...
def _turn_sigterm_into_systemexit(): # pragma: no cover """ Attempts to turn a SIGTERM exception into a SystemExit exception. """ try: import signal except ImportError: return def handle_term(signo, frame): raise SystemExit signal.signal(signal.SIGTERM, handle_term)
def wsgiref_server_runner(wsgi_app, global_conf, **kw): # pragma: no cover """ Entry point for wsgiref's WSGI server Additional parameters: ``certfile``, ``keyfile`` Optional SSL certificate file and host key file names. You can generate self-signed test files as follows: ...
def cherrypy_server_runner( app, global_conf=None, host='127.0.0.1', port=None, ssl_pem=None, protocol_version=None, numthreads=None, server_name=None, max=None, request_queue_size=None, timeout=None ): # pragma: no cover """ Entry point for CherryPy's WSGI server Serves the...
def parse_vars(self, args): """ Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}`` """ result = {} for arg in args: if '=' not in arg: raise ValueError( 'Variable assignment %r invalid (no "=")' ...
def get_fixed_argv(self): # pragma: no cover """Get proper arguments for re-running the command. This is primarily for fixing some issues under Windows. First, there was a bug in Windows when running an executable located at a path with a space in it. This has become a non-iss...
def main(): 'Main function. Handles delegation to other functions.' logging.basicConfig() type_choices = {'any': constants.PACKAGE_ANY, 'extension': constants.PACKAGE_EXTENSION, 'theme': constants.PACKAGE_THEME, 'dictionary': constants.PACKAGE_DI...
def package_contents(self): 'Returns a dictionary of file information' if self.contents_cache: return self.contents_cache # Get a list of ZipInfo objects. files = self.zf.infolist() out_files = {} # Iterate through each file in the XPI. for file_ in...