def test_indent_default(self):
# Test default indenting of lines that are not whitespace only
prefix = ' '
expected = (
# Basic test case
" Hi.\n This is a test.\n Testing.",
# Include a blank line
" Hi.\n This is a test.\n\n Testing.",
# Include leading and trailing blank lines
"\n Hi.\n This is a test.\n Testing.\n",
# Use Windows line endings
" Hi.\r\n This is a test.\r\n Testing.\r\n",
# Pathological case
"\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n",
)
for text, expect in zip(self.CASES, expected):
self.assertEqual(indent(text, prefix), expect)
python类indent()的实例源码
def test_indent_explicit_default(self):
# Test default indenting of lines that are not whitespace only
prefix = ' '
expected = (
# Basic test case
" Hi.\n This is a test.\n Testing.",
# Include a blank line
" Hi.\n This is a test.\n\n Testing.",
# Include leading and trailing blank lines
"\n Hi.\n This is a test.\n Testing.\n",
# Use Windows line endings
" Hi.\r\n This is a test.\r\n Testing.\r\n",
# Pathological case
"\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n",
)
for text, expect in zip(self.CASES, expected):
self.assertEqual(indent(text, prefix, None), expect)
def test_indent_all_lines(self):
# Add 'prefix' to all lines, including whitespace-only ones.
prefix = ' '
expected = (
# Basic test case
" Hi.\n This is a test.\n Testing.",
# Include a blank line
" Hi.\n This is a test.\n \n Testing.",
# Include leading and trailing blank lines
" \n Hi.\n This is a test.\n Testing.\n",
# Use Windows line endings
" Hi.\r\n This is a test.\r\n Testing.\r\n",
# Pathological case
" \n Hi.\r\n This is a test.\n \r\n Testing.\r\n \n",
)
predicate = lambda line: True
for text, expect in zip(self.CASES, expected):
self.assertEqual(indent(text, prefix, predicate), expect)
def test_indent_empty_lines(self):
# Add 'prefix' solely to whitespace-only lines.
prefix = ' '
expected = (
# Basic test case
"Hi.\nThis is a test.\nTesting.",
# Include a blank line
"Hi.\nThis is a test.\n \nTesting.",
# Include leading and trailing blank lines
" \nHi.\nThis is a test.\nTesting.\n",
# Use Windows line endings
"Hi.\r\nThis is a test.\r\nTesting.\r\n",
# Pathological case
" \nHi.\r\nThis is a test.\n \r\nTesting.\r\n \n",
)
predicate = lambda line: not line.strip()
for text, expect in zip(self.CASES, expected):
self.assertEqual(indent(text, prefix, predicate), expect)
def format_assignment_gist(recording, debug=False):
"""Given a single recording, format it into a markdown file.
Each recording will only have one student.
Returns a {content: str, student: str, type: str} dict.
"""
try:
files = format_files_list(recording.get('files', {}))
warnings = format_warnings(recording.get('warnings', {}).items())
header = format_header(recording, warnings)
output = (header + files) + '\n\n'
except Exception as err:
if debug:
raise err
output = indent(traceback.format_exc(), ' ' * 4) + '\n\n'
return {
'content': output,
'student': recording['student'],
'type': 'md',
}
def format_file(filename, file_info):
contents = format_file_contents(file_info.get('contents', ''), file_info) + '\n'
compilation = format_file_compilation(file_info.get('compilation', [])) + '\n'
test_results = format_file_results(file_info.get('result', [])) + '\n'
if file_info.get('last modified', None):
last_modified = ' ({})'.format(file_info['last modified'])
else:
last_modified = ''
file_header = '## {}{}\n'.format(filename, last_modified)
if file_info['missing']:
note = 'File not found. `ls .` says that these files exist:\n'
directory_listing = indent('\n'.join(file_info.get('other files', [])), ' ' * 4)
if file_info['optional']:
file_header = file_header.strip()
file_header += ' (**optional submission**)\n'
return '\n'.join([file_header, note, directory_listing + '\n\n'])
return '\n'.join([file_header, contents, compilation, test_results])
def format_assignment_markdown(recording, debug=False):
"""Given a single recording, format it into a markdown file.
Each recording will only have one student.
Returns a {content: str, student: str, type: str, assignment: str} dict.
"""
try:
files = format_files_list(recording.get('files', {}))
warnings = format_warnings(recording.get('warnings', {}).items())
header = format_header(recording, warnings)
output = (header + files) + '\n\n'
except Exception as err:
if debug:
raise err
output = indent(traceback.format_exc(), ' ' * 4) + '\n\n'
return {
'assignment': recording['spec'],
'content': output,
'student': recording['student'],
'type': 'md',
}
def format_file(filename, file_info):
contents = format_file_contents(file_info.get('contents', ''), file_info) + '\n'
compilation = format_file_compilation(file_info.get('compilation', [])) + '\n'
test_results = format_file_results(file_info.get('result', [])) + '\n'
if file_info.get('last modified', None):
last_modified = ' ({})'.format(file_info['last modified'])
else:
last_modified = ''
file_header = '## {}{}\n'.format(filename, last_modified)
if file_info['missing']:
note = 'File not found. `ls .` says that these files exist:\n'
directory_listing = indent('\n'.join(file_info.get('other files', [])), ' ' * 4)
if file_info['optional']:
file_header = file_header.strip()
file_header += ' (**optional submission**)\n'
return '\n'.join([file_header, note, directory_listing + '\n\n'])
return '\n'.join([file_header, contents, compilation, test_results])
def format_description(content, width=70, indent=8, indent_first=False):
"""Format documentation description"""
# TODO: document, test, and use
lines = content.splitlines()
def format_line(line):
if line.startswith('-'):
return textwrap.indent(textwrap.fill(line, width - indent - 2),
(indent + 2) * ' ')[2:]
else:
return textwrap.indent(textwrap.fill(line, width - indent),
indent * ' ')
result = '\n'.join(format_line(line) for line in lines if line)
if not indent_first:
result = result.lstrip()
return result
def add_param_docs(param_map):
"""
Append documentation from FLAG_MAP to a function's docstring.
:param param_map:
A mapping of argument names (strings) to FlagInfo objects.
:return:
A decorator that appends flag information to a function's docstring.
"""
def decorator(func):
func.__doc__ = textwrap.dedent(func.__doc__) + '\n'.join(
':param {}:\n{}'.format(name, textwrap.indent(arg.doc, ' '))
for name, arg in param_map.items())
return func
return decorator
# Mypy generates messages in the format:
# blabla.py: note: In function "f":
# blabla.py:2: error: Unsupported operand types for ...
# The "note" messages are only adding info coala should already know,
# so discard those. We're only capturing the errors.
def write(self, msg, depth=0):
if depth:
prefix = self.INDENT * depth
msg = indent(msg, prefix)
return super(CodeWriter, self).write(msg)
def buildFacade(schema):
cls = type(schema.name, (Type,), dict(name=schema.name,
version=schema.version,
schema=schema))
source = """
class {name}Facade(Type):
name = '{name}'
version = {version}
schema = {schema}
""".format(name=schema.name,
version=schema.version,
schema=textwrap.indent(pprint.pformat(schema), " "))
return cls, source
def __str__ (self):
out = ''
metadata = self.parse_metadata()
out += 'TAB: {}\n'.format(metadata['name'])
for k,v in sorted(metadata.items()):
if k == 'name':
continue
out += ' {}: {}\n'.format(k,v)
out += ' supported architectures: {}\n'.format(', '.join(self.get_supported_architectures()))
out += ' TBF Header\n'
out += textwrap.indent(str(self.get_tbf_header()), ' ')
return out
def __str__(self):
return "{}: {}\n".format(
self.tag and self.tag.name,
self.tag and self.tag.text_content
) + indent("".join(str(child) for child in self.children), " " * 4)
def str(self, highlight=False) -> str:
s = ''
if self.name:
s = sformat(self.name, sformat.blue, apply=highlight) + ': '
s += pformat(self.value, indent=4, highlight=highlight)
suffix = (
' ({0.value.__class__.__name__}) {1}'
.format(self, ' '.join('{}={}'.format(k, v) for k, v in self.extra))
.rstrip(' ') # trailing space if extra is empty
)
s += sformat(suffix, sformat.dim, apply=highlight)
return s
def _wrap_parse(code, filename):
"""
async wrapper is required to avoid await calls raising a SyntaxError
"""
code = 'async def wrapper():\n' + indent(code, ' ')
return ast.parse(code, filename=filename).body[0].body[0].value
def indent(text, prefix, predicate=None):
if predicate is None:
def predicate(line):
return line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())