]> git.madduck.net Git - etc/vim.git/blob - src/black/output.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

blib2to3: support unparenthesized wulruses in more places (#2447)
[etc/vim.git] / src / black / output.py
1 """Nice output for Black.
2
3 The double calls are for patching purposes in tests.
4 """
5
6 import json
7 from typing import Any, Optional
8 from mypy_extensions import mypyc_attr
9 import tempfile
10
11 from click import echo, style
12
13
14 def _out(message: Optional[str] = None, nl: bool = True, **styles: Any) -> None:
15     if message is not None:
16         if "bold" not in styles:
17             styles["bold"] = True
18         message = style(message, **styles)
19     echo(message, nl=nl, err=True)
20
21
22 def _err(message: Optional[str] = None, nl: bool = True, **styles: Any) -> None:
23     if message is not None:
24         if "fg" not in styles:
25             styles["fg"] = "red"
26         message = style(message, **styles)
27     echo(message, nl=nl, err=True)
28
29
30 def out(message: Optional[str] = None, nl: bool = True, **styles: Any) -> None:
31     _out(message, nl=nl, **styles)
32
33
34 def err(message: Optional[str] = None, nl: bool = True, **styles: Any) -> None:
35     _err(message, nl=nl, **styles)
36
37
38 def ipynb_diff(a: str, b: str, a_name: str, b_name: str) -> str:
39     """Return a unified diff string between each cell in notebooks `a` and `b`."""
40     a_nb = json.loads(a)
41     b_nb = json.loads(b)
42     diff_lines = [
43         diff(
44             "".join(a_nb["cells"][cell_number]["source"]) + "\n",
45             "".join(b_nb["cells"][cell_number]["source"]) + "\n",
46             f"{a_name}:cell_{cell_number}",
47             f"{b_name}:cell_{cell_number}",
48         )
49         for cell_number, cell in enumerate(a_nb["cells"])
50         if cell["cell_type"] == "code"
51     ]
52     return "".join(diff_lines)
53
54
55 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
56     """Return a unified diff string between strings `a` and `b`."""
57     import difflib
58
59     a_lines = [line for line in a.splitlines(keepends=True)]
60     b_lines = [line for line in b.splitlines(keepends=True)]
61     diff_lines = []
62     for line in difflib.unified_diff(
63         a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5
64     ):
65         # Work around https://bugs.python.org/issue2142
66         # See:
67         # https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html
68         if line[-1] == "\n":
69             diff_lines.append(line)
70         else:
71             diff_lines.append(line + "\n")
72             diff_lines.append("\\ No newline at end of file\n")
73     return "".join(diff_lines)
74
75
76 def color_diff(contents: str) -> str:
77     """Inject the ANSI color codes to the diff."""
78     lines = contents.split("\n")
79     for i, line in enumerate(lines):
80         if line.startswith("+++") or line.startswith("---"):
81             line = "\033[1;37m" + line + "\033[0m"  # bold white, reset
82         elif line.startswith("@@"):
83             line = "\033[36m" + line + "\033[0m"  # cyan, reset
84         elif line.startswith("+"):
85             line = "\033[32m" + line + "\033[0m"  # green, reset
86         elif line.startswith("-"):
87             line = "\033[31m" + line + "\033[0m"  # red, reset
88         lines[i] = line
89     return "\n".join(lines)
90
91
92 @mypyc_attr(patchable=True)
93 def dump_to_file(*output: str, ensure_final_newline: bool = True) -> str:
94     """Dump `output` to a temporary file. Return path to the file."""
95     with tempfile.NamedTemporaryFile(
96         mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
97     ) as f:
98         for lines in output:
99             f.write(lines)
100             if ensure_final_newline and lines and lines[-1] != "\n":
101                 f.write("\n")
102     return f.name