def print_result(ctx, obj): """ Dump a result to the console or an output file.""" text = obj if isinstance(text, dict): if isinstance(text, Bunch): # Debunchify for ``pformat`` text = dict(text.copy()) for key, val in text.items(): if isinstance(val, Bunch): text[key] = dict(val) #text = pformat(text) text = json.dumps(text, indent=2, sort_keys=True) elif isinstance(text, list): text = json.dumps(text, indent=2, sort_keys=True) if not isinstance(text, string_types): text = repr(text) if ctx.obj.serializer in SERIALIZERS_NEED_NL: text += '\n' #if isinstance(text, text_type): # text = text.encode('utf-8') try: (ctx.obj.outfile or sys.stdout).write(text) except EnvironmentError as cause: raise click.LoggedFailure('Error while writing "{}" ({})'.format( getattr(ctx.obj.outfile or object(), 'name', '<stream>'), cause))
def _make_etree(body, content_format='storage', attrs=None): """Create an ElementTree from a page's body.""" attrs = (attrs or {}).copy() attrs.update({ 'xmlns:ac': 'http://www.atlassian.com/schema/confluence/4/ac/', 'xmlns:ri': 'http://www.atlassian.com/schema/confluence/4/ri/', }) xml_body = re.sub( r'&(?!(amp|lt|gt|quot|apos))([a-zA-Z0-9]+);', lambda cref: '&#{};'. format(htmlentitydefs.name2codepoint[cref.group(2)]), body) #print(body.encode('utf8')) xmldoc = u'<{root} {attrs}>{body}</{root}>'.format( root=content_format, attrs=' '.join('{}={}'.format(k, quoteattr(v)) for k, v in sorted(attrs.items())), body=xml_body) parser = (XMLParser if content_format == 'storage' else HTMLParser)( remove_blank_text=True) try: return fromstring(xmldoc, parser) except XMLSyntaxError as cause: raise click.LoggedFailure('{}\n{}'.format( cause, '\n'.join([ '{:7d} {}'.format(i + 1, k) for i, k in enumerate(xmldoc.splitlines()) ])))
def _apply_tidy_regex_rules(body, log=None): """Return tidied body after applying regex rules.""" body = body.replace(u'\u00A0', ' ') for name, rule, subst in TIDY_REGEX_RULES: length = len(body) try: body, count = rule.subn(subst, body) except re.error as cause: raise click.LoggedFailure('Error "{}" in "{}" replacement: {} => {}'.format( cause, name, rule.pattern, subst, )) if count and log: length -= len(body) log.info('Replaced %d matche(s) of "%s" (%d chars %s)', count, name, abs(length), "added" if length < 0 else "removed") return body