/usr/lib/python3/dist-packages/cement/utils/misc.py is in python3-cement 2.10.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """Misc utilities."""
import os
import sys
import logging
import hashlib
from textwrap import TextWrapper
from random import random
def rando(salt=None):
"""
Generate a random MD5 hash for whatever purpose. Useful for testing
or any other time that something random is required.
:param salt: Optional 'salt', if None then random() is used.
:returns: Random MD5 hash (str).
"""
if salt is None:
salt = random()
return hashlib.md5(str(salt).encode()).hexdigest()
class MinimalLogger(object):
def __init__(self, namespace, debug, *args, **kw):
self.namespace = namespace
self.backend = logging.getLogger(namespace)
formatter = logging.Formatter(
"%(asctime)s (%(levelname)s) %(namespace)s : %(message)s"
)
console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(logging.INFO)
self.backend.setLevel(logging.INFO)
# FIX ME: really don't want to hard check sys.argv like this but
# can't figure any better way get logging started (only for debug)
# before the app logging is setup.
if '--debug' in sys.argv or debug:
console.setLevel(logging.DEBUG)
self.backend.setLevel(logging.DEBUG)
self.backend.addHandler(console)
def _get_logging_kwargs(self, namespace, **kw):
if not namespace:
namespace = self.namespace
if 'extra' in kw.keys() and 'namespace' in kw['extra'].keys():
pass
elif 'extra' in kw.keys() and 'namespace' not in kw['extra'].keys():
kw['extra']['namespace'] = namespace
else:
kw['extra'] = dict(namespace=namespace)
return kw
@property
def logging_is_enabled(self):
if 'CEMENT_FRAMEWORK_LOGGING' in os.environ.keys():
if is_true(os.environ['CEMENT_FRAMEWORK_LOGGING']):
res = True
else:
res = False
else:
res = True
return res
def info(self, msg, namespace=None, **kw):
if self.logging_is_enabled:
kwargs = self._get_logging_kwargs(namespace, **kw)
self.backend.info(msg, **kwargs)
def warning(self, msg, namespace=None, **kw):
if self.logging_is_enabled:
kwargs = self._get_logging_kwargs(namespace, **kw)
self.backend.warning(msg, **kwargs)
def warn(self, msg, namespace=None, **kw):
self.warning(msg, namespace, **kw)
def error(self, msg, namespace=None, **kw):
if self.logging_is_enabled:
kwargs = self._get_logging_kwargs(namespace, **kw)
self.backend.error(msg, **kwargs)
def fatal(self, msg, namespace=None, **kw):
if self.logging_is_enabled:
kwargs = self._get_logging_kwargs(namespace, **kw)
self.backend.fatal(msg, **kwargs)
def debug(self, msg, namespace=None, **kw):
if self.logging_is_enabled:
kwargs = self._get_logging_kwargs(namespace, **kw)
self.backend.debug(msg, **kwargs)
def init_defaults(*sections):
"""
Returns a standard dictionary object to use for application defaults.
If sections are given, it will create a nested dict for each section name.
:arg sections: Section keys to create nested dictionaries for.
:returns: Dictionary of nested dictionaries (sections)
:rtype: dict
.. code-block:: python
from cement.core import foundation
from cement.utils.misc import init_defaults
defaults = init_defaults('myapp', 'section2', 'section3')
defaults['myapp']['debug'] = False
defaults['section2']['foo'] = 'bar
defaults['section3']['foo2'] = 'bar2'
app = foundation.CementApp('myapp', config_defaults=defaults)
"""
defaults = dict()
for section in sections:
defaults[section] = dict()
return defaults
def minimal_logger(namespace, debug=False):
"""
Setup just enough for cement to be able to do debug logging. This is the
logger used by the Cement framework, which is setup and accessed before
the application is functional (and more importantly before the
applications log handler is usable).
:param namespace: The logging namespace. This is generally '__name__' or
anything you want.
:param debug: Toggle debug output. Default: False
:type debug: boolean
:returns: Logger object
.. code-block:: python
from cement.utils.misc import minimal_logger
LOG = minimal_logger('cement')
LOG.debug('This is a debug message')
"""
return MinimalLogger(namespace, debug)
def is_true(item):
"""
Given a value, determine if it is one of [True, 'True', 'true', 1, '1'].
:param item: The item to convert to a boolean.
:returns: True if `item` is in ``[True, 'True', 'true', 1, '1']``, False
otherwise.
:rtype: boolean
"""
if item in [True, 'True', 'true', 1, '1']:
return True
else:
return False
def wrap(text, width=77, indent='', long_words=False, hyphens=False):
"""
Wrap text for cleaner output (this is a simple wrapper around
`textwrap.TextWrapper` in the standard library).
:param text: The text to wrap
:param width: The max width of a line before breaking
:param indent: String to prefix subsequent lines after breaking
:param long_words: Break on long words
:param hyphens: Break on hyphens
:returns: str(text)
"""
if sys.version_info[0] < 3: # pragma: no cover # noqa
types = [str, unicode] # pragma: no cover # noqa
else: # pragma: no cover # noqa
types = [str] # pragma: no cover # noqa
if type(text) not in types:
raise TypeError("Argument `text` must be one of [str, unicode].")
wrapper = TextWrapper(subsequent_indent=indent, width=width,
break_long_words=long_words,
break_on_hyphens=hyphens)
return wrapper.fill(text)
|