Python源码示例:black.FileMode()
示例1
def format_signature(
signature_start: str, signature_end: str, max_line_length: int = 110
):
"""pretty formatting to avoid long signatures on one single line"""
# first, we make it look like a real function declaration.
fake_signature_start = 'x' * len(signature_start)
fake_signature = fake_signature_start + signature_end
fake_python_code = f'def {fake_signature}:\n pass\n'
# we format with black
mode = black.FileMode(line_length=max_line_length)
formatted_fake_python_code = black.format_str(fake_python_code, mode=mode)
# we make the final, multiline signature
new_signature_end = extract_signature_end(formatted_fake_python_code)
return signature_start + new_signature_end
示例2
def apply_black(code: str, python_version: PythonVersion) -> str:
root = black.find_project_root((Path().resolve(),))
path = root / "pyproject.toml"
if path.is_file():
value = str(path)
pyproject_toml = toml.load(value)
config = pyproject_toml.get("tool", {}).get("black", {})
else:
config = {}
return black.format_str(
code,
mode=black.FileMode(
target_versions={BLACK_PYTHON_VERSION[python_version]},
line_length=config.get("line-length", black.DEFAULT_LINE_LENGTH),
string_normalization=not config.get("skip-string-normalization", True),
),
)
示例3
def test_format_file_contents(self) -> None:
empty = ""
mode = black.FileMode()
with self.assertRaises(black.NothingChanged):
black.format_file_contents(empty, mode=mode, fast=False)
just_nl = "\n"
with self.assertRaises(black.NothingChanged):
black.format_file_contents(just_nl, mode=mode, fast=False)
same = "j = [1, 2, 3]\n"
with self.assertRaises(black.NothingChanged):
black.format_file_contents(same, mode=mode, fast=False)
different = "j = [1,2,3]"
expected = same
actual = black.format_file_contents(different, mode=mode, fast=False)
self.assertEqual(expected, actual)
invalid = "return if you can"
with self.assertRaises(black.InvalidInput) as e:
black.format_file_contents(invalid, mode=mode, fast=False)
self.assertEqual(str(e.exception), "Cannot parse: 1:7: return if you can")
示例4
def test_single_file_force_pyi(self) -> None:
reg_mode = black.FileMode()
pyi_mode = black.FileMode(is_pyi=True)
contents, expected = read_data("force_pyi")
with cache_dir() as workspace:
path = (workspace / "file.py").resolve()
with open(path, "w") as fh:
fh.write(contents)
self.invokeBlack([str(path), "--pyi"])
with open(path, "r") as fh:
actual = fh.read()
# verify cache with --pyi is separate
pyi_cache = black.read_cache(pyi_mode)
self.assertIn(path, pyi_cache)
normal_cache = black.read_cache(reg_mode)
self.assertNotIn(path, normal_cache)
self.assertEqual(actual, expected)
示例5
def test_multi_file_force_pyi(self) -> None:
reg_mode = black.FileMode()
pyi_mode = black.FileMode(is_pyi=True)
contents, expected = read_data("force_pyi")
with cache_dir() as workspace:
paths = [
(workspace / "file1.py").resolve(),
(workspace / "file2.py").resolve(),
]
for path in paths:
with open(path, "w") as fh:
fh.write(contents)
self.invokeBlack([str(p) for p in paths] + ["--pyi"])
for path in paths:
with open(path, "r") as fh:
actual = fh.read()
self.assertEqual(actual, expected)
# verify cache with --pyi is separate
pyi_cache = black.read_cache(pyi_mode)
normal_cache = black.read_cache(reg_mode)
for path in paths:
self.assertIn(path, pyi_cache)
self.assertNotIn(path, normal_cache)
示例6
def test_multi_file_force_py36(self) -> None:
reg_mode = black.FileMode()
py36_mode = black.FileMode(target_versions=black.PY36_VERSIONS)
source, expected = read_data("force_py36")
with cache_dir() as workspace:
paths = [
(workspace / "file1.py").resolve(),
(workspace / "file2.py").resolve(),
]
for path in paths:
with open(path, "w") as fh:
fh.write(source)
self.invokeBlack([str(p) for p in paths] + PY36_ARGS)
for path in paths:
with open(path, "r") as fh:
actual = fh.read()
self.assertEqual(actual, expected)
# verify cache with --target-version is separate
pyi_cache = black.read_cache(py36_mode)
normal_cache = black.read_cache(reg_mode)
for path in paths:
self.assertIn(path, pyi_cache)
self.assertNotIn(path, normal_cache)
示例7
def format_file(
filename: str, black_mode: black.FileMode, skip_errors: bool,
) -> int:
with open(filename, encoding='UTF-8') as f:
contents = f.read()
new_contents, errors = format_str(contents, black_mode)
for error in errors:
lineno = contents[:error.offset].count('\n') + 1
print(f'{filename}:{lineno}: code block parse error {error.exc}')
if errors and not skip_errors:
return 1
if contents != new_contents:
print(f'{filename}: Rewriting...')
with open(filename, 'w', encoding='UTF-8') as f:
f.write(new_contents)
return 1
else:
return 0
示例8
def handle_options(**options):
import black
file_mode_change_version = version.parse("19.3b0")
current_black_version = version.parse(black.__version__)
if current_black_version >= file_mode_change_version:
return {"mode": black.FileMode(**options)}
else:
return options
示例9
def format_blueprint_command(bp_file):
path = pathlib.Path(bp_file)
LOG.debug("Formatting blueprint {} using black".format(path))
if format_file_in_place(
path, fast=False, mode=FileMode(), write_back=WriteBack.DIFF
):
LOG.info("Patching above diff to blueprint - {}".format(path))
format_file_in_place(
path, fast=False, mode=FileMode(), write_back=WriteBack.YES
)
LOG.info("All done!")
else:
LOG.info("Blueprint {} left unchanged.".format(path))
示例10
def _format_script(script):
try:
import black
formatter = partial(
black.format_str, mode=black.FileMode(line_length=80)
)
except ImportError:
# use autopep8 for python3.5
import autopep8
formatter = partial(
autopep8.fix_code, options={"aggressive": 1}
)
return formatter(script)
示例11
def format_text(*, text, config):
mode = black.FileMode(
target_versions=config["target_version"],
line_length=config["line_length"],
is_pyi=config["pyi"],
string_normalization=not config["skip_string_normalization"],
)
return black.format_file_contents(text, fast=config["fast"], mode=mode)
示例12
def _format_code(code):
return format_str(src_contents=code, mode=FileMode())
示例13
def black(self, line, cell):
"""Magic command to format the IPython cell."""
args = magic_arguments.parse_argstring(self.black, line)
line_length = args.line_length
if cell:
try:
from black import FileMode
mode = FileMode(line_length=line_length)
formatted = format_str(src_contents=cell, mode=mode)
except TypeError:
formatted = format_str(src_contents=cell, line_length=line_length)
if formatted and formatted[-1] == "\n":
formatted = formatted[:-1]
self.shell.set_next_input(formatted, replace=True)
示例14
def checkSourceFile(self, name: str) -> None:
path = THIS_DIR.parent / name
source, expected = read_data(str(path), data=False)
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
self.assertFalse(ff(path))
示例15
def test_empty(self) -> None:
source = expected = ""
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例16
def test_piping(self) -> None:
source, expected = read_data("src/black/__init__", data=False)
result = BlackRunner().invoke(
black.main,
["-", "--fast", f"--line-length={black.DEFAULT_LINE_LENGTH}"],
input=BytesIO(source.encode("utf8")),
)
self.assertEqual(result.exit_code, 0)
self.assertFormatEqual(expected, result.output)
black.assert_equivalent(source, result.output)
black.assert_stable(source, result.output, black.FileMode())
示例17
def test_function(self) -> None:
source, expected = read_data("function")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例18
def test_function2(self) -> None:
source, expected = read_data("function2")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例19
def test_expression(self) -> None:
source, expected = read_data("expression")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例20
def test_pep_572(self) -> None:
source, expected = read_data("pep_572")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, black.FileMode())
if sys.version_info >= (3, 8):
black.assert_equivalent(source, actual)
示例21
def test_expression_ff(self) -> None:
source, expected = read_data("expression")
tmp_file = Path(black.dump_to_file(source))
try:
self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES))
with open(tmp_file, encoding="utf8") as f:
actual = f.read()
finally:
os.unlink(tmp_file)
self.assertFormatEqual(expected, actual)
with patch("black.dump_to_file", dump_to_stderr):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例22
def test_fstring(self) -> None:
source, expected = read_data("fstring")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例23
def test_pep_570(self) -> None:
source, expected = read_data("pep_570")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, black.FileMode())
if sys.version_info >= (3, 8):
black.assert_equivalent(source, actual)
示例24
def test_docstring(self) -> None:
source, expected = read_data("docstring")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例25
def test_long_strings(self) -> None:
"""Tests for splitting long strings."""
source, expected = read_data("long_strings")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例26
def test_long_strings__edge_case(self) -> None:
"""Edge-case tests for splitting long strings."""
source, expected = read_data("long_strings__edge_case")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例27
def test_long_strings__regression(self) -> None:
"""Regression tests for splitting long strings."""
source, expected = read_data("long_strings__regression")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例28
def test_slices(self) -> None:
source, expected = read_data("slices")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例29
def test_comments2(self) -> None:
source, expected = read_data("comments2")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
示例30
def test_comments3(self) -> None:
source, expected = read_data("comments3")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())