"""Generic pretty display utils.This module defines a print function that's supposed to be able to pretty-printanything, as well as a pretty diff printer."""importosimportsystry:importjsonlightasjsonexceptImportError:importjson_print=printdefhighlight(string,lexer):FORCE_COLOR=bool(os.getenv('FORCE_COLOR',''))ifnotsys.stdout.isatty()andnotFORCE_COLOR:returnstringtry:importpygmentsimportpygments.lexersimportpygments.formattersexceptImportError:returnstringformatter=pygments.formatters.TerminalFormatter()lexer=getattr(pygments.lexers,lexer+'Lexer')()returnpygments.highlight(string,lexer,formatter)defyaml_dump(data):importyamlifisinstance(data,dict):# ensure that objects inheriting from dict render nicelydata=dict(data)returnyaml.dump(data,indent=4,width=float('inf'))defyaml_highlight(yaml_string):returnhighlight(yaml_string,'Yaml')
[docs]defrender(arg):""" Try to render arg as yaml. If the arg has a ``.json()`` method, it'll be called. If it is parseable as JSON then it'l be parsed as such. Then, it'll be dumped as colored YAML. Set the env var `FORCE_COLOR` to anything to force into printing colors even if terminal is non-interactive (ie. gitlab-ci) .. code-block:: python # pretty render some_object print(cli2.render(some_object)) """try:# deal with response objectsarg=arg.json()except:# noqapasstry:# is this json?arg=json.loads(arg)except:# noqapass# does this wants to show specific data to cli2?try:arg=arg.cli2_displayexceptAttributeError:passstring=argifisinstance(arg,str)elseyaml_dump(arg)returnyaml_highlight(string)
[docs]defprint(*args,**kwargs):""" Try to print the :py:func:`render`'ed args, pass the kwargs to actual print method. .. code-block:: python # pretty print some_object cli2.print(some_object) """forarginargs:_print(render(arg),**kwargs)