def words(text, normalize=None, split="_", decamel=False): """Words extracted from `text` (split on underscore character as well by default) Args: text: Text to extract words from normalize (callable | None): Optional function to apply on each word split (str | None): Optional extra character to split words on decamel (bool): If True, extract CamelCase words as well Returns: (list): Extracted words """ if not text: return [] if isinstance(text, list): result = [] for line in text: result.extend(words(line, normalize=normalize, split=split, decamel=decamel)) return result strings = _R.lc.rx_words.split(stringified(text)) strings = flattened(strings, split=split, strip=True) if decamel: strings = flattened(_R.lc.rx_camel_cased_words.findall(s) for s in strings) if normalize: strings = [normalize(s) for s in strings] return strings
def _represented_cell(text, missing_color): if text is None: return _R.colored("-missing-", missing_color) if text is UNSET: return _R.colored("UNSET", missing_color) return stringified(text)
def _run_main(self, main, args): if _ClickCommand is not None and isinstance(main, _ClickCommand): if "LANG" not in os.environ: # Avoid click complaining about unicode for tests that mock env vars os.environ["LANG"] = "en_US.UTF-8" runner = _CliRunner() r = runner.invoke(main, args=args) return ClickWrapper(r.output, None, r.exit_code, r.exception) if callable(main): result = ClickWrapper(None, None, None, None) try: result.stdout = main() result.exit_code = 0 except AssertionError: raise except SystemExit as e: if isinstance(e.code, int): result.exit_code = e.code else: result.exit_code = 1 result.stderr = stringified(e) except BaseException as e: result.exit_code = 1 result.exception = e result.stderr = stringified(e) return result if isinstance(main, str): script = self._resolved_script(main) if not script: assert False, "Can't find script '%s', invalid main" % script r = runez.run(sys.executable, script, *args, fatal=False) return ClickWrapper(r.output, r.error, r.exit_code, r.exc_info) assert False, "Can't invoke invalid main: %s" % main
def get_str(self, key, default=None): """ Args: key (str | None): Key to lookup default (str | None): Default to use if key is not configured Returns: (str | None): Value of key, if defined """ value = self.get(key, default=default) if value is None: return None return stringified(value)
def __init__(self, text, family=None): """ Args: text: Text describing desired python (note: an empty or None `text` will yield a generic "cpython:" spec) family (str | None): Additional text to examine to determine python family """ text = stringified(text, none="").strip() self.text = text if not text or text == "invoker": self.family = guess_family(family or sys.version) self.canonical = "invoker" self.version = get_current_version() return if _is_path(text): self.family = guess_family(family or text) self.canonical = resolved_path(text) return m = _R.lc.rx_spec.match(text) if not m: m = _R.lc.rx_family.match(text) if m: self.family = guess_family(family or m.group(1)) self.canonical = "%s:" % self.family else: self.canonical = "?%s" % text return version_text = m.group(3) if version_text and version_text.endswith("+"): self.is_min_spec = "+" version_text = version_text[:-1] if version_text: if len(version_text) > 1 and "." not in version_text: version_text = "%s.%s" % (version_text[0], version_text[1:]) self.version = Version.from_text(version_text, strict=True) if self.version: self.family = guess_family(family or m.group(1)) self.canonical = "%s:%s%s" % (self.family, self.version or "", self.is_min_spec) else: self.canonical = "?%s" % text
def __call__(self, text, size=None): """ Allows for convenient call of the form: >>> import runez >>> runez.blue("foo") 'foo' """ if size: text = short(text, size=size) else: text = stringified(text) if not text: return "" return self.rendered(text)
def _formatted_text(text, props, strict=False, max_depth=3): """ Args: text (str): Text with '{...}' placeholders to be resolved props (dict): Available values Returns: (str): '{...}' placeholders resolved from given `props` """ if not text: return text if text.startswith("~"): text = os.path.expanduser(text) if "{" not in text: return text definitions = {} markers = _R.lc.rx_format_markers.findall(text) while markers: key = markers.pop() if key in definitions: continue val = props.get(key) if strict and val is None: return None val = stringified(val) if val is not None else "{%s}" % key markers.extend(m for m in _R.lc.rx_format_markers.findall(val) if m not in definitions) definitions[key] = val if not max_depth or not isinstance(max_depth, int) or max_depth <= 0: return text result = dict((k, _format_recursive(k, v, definitions, max_depth)) for k, v in definitions.items()) return text.format(**result)
def protected_main(main, debug_stacktrace=False, no_stacktrace=None): """Convenience wrapper for a click main() function Args: main (callable): 'main' function to invoke debug_stacktrace (bool): If True, show stack traces only with --debug runs no_stacktrace (list | None): Do not show stack trace for give Exception types """ try: return main() except KeyboardInterrupt: sys.stderr.write( ColorManager.fg.red("\n\nAborted\n\n") ) # No need to show stack trace on a KeyboardInterrupt sys.exit(1) except NotImplementedError as e: msg = stringified( e ) or "Not implemented yet" # Convenience pretty-print of a `raise NotImplementedError(...)` sys.stderr.write(ColorManager.fg.red("\n%s\n\n" % msg)) sys.exit(1) except Exception as e: if getattr(e, "errno", None) == errno.EPIPE: sys.exit( 0 ) # Broken pipe is OK, happens when output is piped to another command that closes input early, like `head` logger = logging.exception if (debug_stacktrace and not LogManager.debug) or (no_stacktrace and type(e) in no_stacktrace): logger = logging.error e = ColorManager.fg.red(e) logger(e) # Ensure any uncaught exception gets properly logged sys.exit(1)
def _converted(self, value): return stringified(value)
def formatted(self, value): return stringified(value, none=self.missing)
def __init__(self, index, text=None): self.index = index self.text = None if text is None else stringified(text) self.shown = True
def __repr__(self): if not self.providers: return "empty" return ", ".join(stringified(p) for p in self.providers)
def __repr__(self): return stringified(self.base_url or self.session)
def text(self): return stringified(self.content)