| 1 |
python3 << EndPython3 |
| 2 |
import collections |
| 3 |
import os |
| 4 |
import sys |
| 5 |
import vim |
| 6 |
|
| 7 |
|
| 8 |
def strtobool(text): |
| 9 |
if text.lower() in ["y", "yes", "t", "true", "on", "1"]: |
| 10 |
return True |
| 11 |
if text.lower() in ["n", "no", "f", "false", "off", "0"]: |
| 12 |
return False |
| 13 |
raise ValueError(f"{text} is not convertible to boolean") |
| 14 |
|
| 15 |
|
| 16 |
class Flag(collections.namedtuple("FlagBase", "name, cast")): |
| 17 |
@property |
| 18 |
def var_name(self): |
| 19 |
return self.name.replace("-", "_") |
| 20 |
|
| 21 |
@property |
| 22 |
def vim_rc_name(self): |
| 23 |
name = self.var_name |
| 24 |
if name == "line_length": |
| 25 |
name = name.replace("_", "") |
| 26 |
return "g:black_" + name |
| 27 |
|
| 28 |
|
| 29 |
FLAGS = [ |
| 30 |
Flag(name="line_length", cast=int), |
| 31 |
Flag(name="fast", cast=strtobool), |
| 32 |
Flag(name="skip_string_normalization", cast=strtobool), |
| 33 |
Flag(name="quiet", cast=strtobool), |
| 34 |
Flag(name="skip_magic_trailing_comma", cast=strtobool), |
| 35 |
Flag(name="preview", cast=strtobool), |
| 36 |
] |
| 37 |
|
| 38 |
|
| 39 |
def _get_python_binary(exec_prefix, pyver): |
| 40 |
try: |
| 41 |
default = vim.eval("g:pymode_python").strip() |
| 42 |
except vim.error: |
| 43 |
default = "" |
| 44 |
if default and os.path.exists(default): |
| 45 |
return default |
| 46 |
if sys.platform[:3] == "win": |
| 47 |
return exec_prefix / "python.exe" |
| 48 |
bin_path = exec_prefix / "bin" |
| 49 |
exec_path = (bin_path / f"python{pyver[0]}.{pyver[1]}").resolve() |
| 50 |
if exec_path.exists(): |
| 51 |
return exec_path |
| 52 |
# It is possible that some environments may only have python3 |
| 53 |
exec_path = (bin_path / "python3").resolve() |
| 54 |
if exec_path.exists(): |
| 55 |
return exec_path |
| 56 |
raise ValueError("python executable not found") |
| 57 |
|
| 58 |
|
| 59 |
def _get_pip(venv_path): |
| 60 |
if sys.platform[:3] == "win": |
| 61 |
return venv_path / "Scripts" / "pip.exe" |
| 62 |
return venv_path / "bin" / "pip" |
| 63 |
|
| 64 |
|
| 65 |
def _get_virtualenv_site_packages(venv_path, pyver): |
| 66 |
if sys.platform[:3] == "win": |
| 67 |
return venv_path / "Lib" / "site-packages" |
| 68 |
if ( |
| 69 |
venv_path.exists() |
| 70 |
and not (venv_path / "lib" / f"python{pyver[0]}.{pyver[1]}").exists() |
| 71 |
): |
| 72 |
# The virtualenv already exists but it doesn't seem to have the expected |
| 73 |
# Python version, so we disregard the requested `pyver` and |
| 74 |
# discover the real Python interpreter from this virtualenv |
| 75 |
import subprocess |
| 76 |
|
| 77 |
result = subprocess.run( |
| 78 |
[_get_python_binary(venv_path, pyver), "--version"], |
| 79 |
stdout=subprocess.PIPE, |
| 80 |
text=True, |
| 81 |
) |
| 82 |
venv_version = result.stdout.split(" ")[1].strip().split(".") |
| 83 |
return ( |
| 84 |
venv_path |
| 85 |
/ "lib" |
| 86 |
/ f"python{venv_version[0]}.{venv_version[1]}" |
| 87 |
/ "site-packages" |
| 88 |
) |
| 89 |
else: |
| 90 |
return venv_path / "lib" / f"python{pyver[0]}.{pyver[1]}" / "site-packages" |
| 91 |
|
| 92 |
|
| 93 |
def _initialize_black_env(upgrade=False): |
| 94 |
if vim.eval("g:black_use_virtualenv ? 'true' : 'false'") == "false": |
| 95 |
if upgrade: |
| 96 |
print("Upgrade disabled due to g:black_use_virtualenv being disabled.") |
| 97 |
print( |
| 98 |
"Either use your system package manager (or pip) to upgrade black" |
| 99 |
" separately," |
| 100 |
) |
| 101 |
print("or modify your vimrc to have 'let g:black_use_virtualenv = 1'.") |
| 102 |
return False |
| 103 |
else: |
| 104 |
# Nothing needed to be done. |
| 105 |
return True |
| 106 |
|
| 107 |
pyver = sys.version_info[:3] |
| 108 |
if pyver < (3, 10): |
| 109 |
print("Sorry, Black requires Python 3.10+ to run.") |
| 110 |
return False |
| 111 |
|
| 112 |
from pathlib import Path |
| 113 |
import subprocess |
| 114 |
import venv |
| 115 |
|
| 116 |
virtualenv_path = Path(vim.eval("g:black_virtualenv")).expanduser() |
| 117 |
virtualenv_site_packages = str( |
| 118 |
_get_virtualenv_site_packages(virtualenv_path, pyver) |
| 119 |
) |
| 120 |
first_install = False |
| 121 |
if not virtualenv_path.is_dir(): |
| 122 |
print("Please wait, one time setup for Black.") |
| 123 |
_executable = sys.executable |
| 124 |
_base_executable = getattr(sys, "_base_executable", _executable) |
| 125 |
try: |
| 126 |
executable = str(_get_python_binary(Path(sys.exec_prefix), pyver)) |
| 127 |
sys.executable = executable |
| 128 |
sys._base_executable = executable |
| 129 |
print(f"Creating a virtualenv in {virtualenv_path}...") |
| 130 |
print( |
| 131 |
"(this path can be customized in .vimrc by setting g:black_virtualenv)" |
| 132 |
) |
| 133 |
venv.create(virtualenv_path, with_pip=True) |
| 134 |
except Exception: |
| 135 |
print( |
| 136 |
"Encountered exception while creating virtualenv (see traceback below)." |
| 137 |
) |
| 138 |
print(f"Removing {virtualenv_path}...") |
| 139 |
import shutil |
| 140 |
|
| 141 |
shutil.rmtree(virtualenv_path) |
| 142 |
raise |
| 143 |
finally: |
| 144 |
sys.executable = _executable |
| 145 |
sys._base_executable = _base_executable |
| 146 |
first_install = True |
| 147 |
if first_install: |
| 148 |
print("Installing Black with pip...") |
| 149 |
if upgrade: |
| 150 |
print("Upgrading Black with pip...") |
| 151 |
if first_install or upgrade: |
| 152 |
subprocess.run( |
| 153 |
[str(_get_pip(virtualenv_path)), "install", "-U", "black"], |
| 154 |
stdout=subprocess.PIPE, |
| 155 |
) |
| 156 |
print("DONE! You are all set, thanks for waiting ✨ 🍰 ✨") |
| 157 |
if first_install: |
| 158 |
print( |
| 159 |
"Pro-tip: to upgrade Black in the future, use the :BlackUpgrade command and" |
| 160 |
" restart Vim.\n" |
| 161 |
) |
| 162 |
if virtualenv_site_packages not in sys.path: |
| 163 |
sys.path.insert(0, virtualenv_site_packages) |
| 164 |
return True |
| 165 |
|
| 166 |
|
| 167 |
if _initialize_black_env(): |
| 168 |
try: |
| 169 |
import black |
| 170 |
except ImportError: |
| 171 |
print(f"Could not import black from any of: {', '.join(sys.path)}.") |
| 172 |
import time |
| 173 |
|
| 174 |
|
| 175 |
def get_target_version(tv): |
| 176 |
if isinstance(tv, black.TargetVersion): |
| 177 |
return tv |
| 178 |
ret = None |
| 179 |
try: |
| 180 |
ret = black.TargetVersion[tv.upper()] |
| 181 |
except KeyError: |
| 182 |
print( |
| 183 |
f"WARNING: Target version {tv!r} not recognized by Black, using default" |
| 184 |
" target" |
| 185 |
) |
| 186 |
return ret |
| 187 |
|
| 188 |
|
| 189 |
def Black(**kwargs): |
| 190 |
""" |
| 191 |
kwargs allows you to override ``target_versions`` argument of |
| 192 |
``black.FileMode``. |
| 193 |
|
| 194 |
``target_version`` needs to be cleaned because ``black.FileMode`` |
| 195 |
expects the ``target_versions`` argument to be a set of TargetVersion enums. |
| 196 |
|
| 197 |
Allow kwargs["target_version"] to be a string to allow |
| 198 |
to type it more quickly. |
| 199 |
|
| 200 |
Using also target_version instead of target_versions to remain |
| 201 |
consistent to Black's documentation of the structure of pyproject.toml. |
| 202 |
""" |
| 203 |
start = time.time() |
| 204 |
configs = get_configs() |
| 205 |
|
| 206 |
black_kwargs = {} |
| 207 |
if "target_version" in kwargs: |
| 208 |
target_version = kwargs["target_version"] |
| 209 |
|
| 210 |
if not isinstance(target_version, (list, set)): |
| 211 |
target_version = [target_version] |
| 212 |
target_version = set( |
| 213 |
filter(lambda x: x, map(lambda tv: get_target_version(tv), target_version)) |
| 214 |
) |
| 215 |
black_kwargs["target_versions"] = target_version |
| 216 |
|
| 217 |
mode = black.FileMode( |
| 218 |
line_length=configs["line_length"], |
| 219 |
string_normalization=not configs["skip_string_normalization"], |
| 220 |
is_pyi=vim.current.buffer.name.endswith(".pyi"), |
| 221 |
magic_trailing_comma=not configs["skip_magic_trailing_comma"], |
| 222 |
preview=configs["preview"], |
| 223 |
**black_kwargs, |
| 224 |
) |
| 225 |
quiet = configs["quiet"] |
| 226 |
|
| 227 |
buffer_str = "\n".join(vim.current.buffer) + "\n" |
| 228 |
try: |
| 229 |
new_buffer_str = black.format_file_contents( |
| 230 |
buffer_str, |
| 231 |
fast=configs["fast"], |
| 232 |
mode=mode, |
| 233 |
) |
| 234 |
except black.NothingChanged: |
| 235 |
if not quiet: |
| 236 |
print( |
| 237 |
"Black: already well formatted, good job. (took" |
| 238 |
f" {time.time() - start:.4f}s)" |
| 239 |
) |
| 240 |
except Exception as exc: |
| 241 |
print(f"Black: {exc}") |
| 242 |
else: |
| 243 |
current_buffer = vim.current.window.buffer |
| 244 |
cursors = [] |
| 245 |
for i, tabpage in enumerate(vim.tabpages): |
| 246 |
if tabpage.valid: |
| 247 |
for j, window in enumerate(tabpage.windows): |
| 248 |
if window.valid and window.buffer == current_buffer: |
| 249 |
cursors.append((i, j, window.cursor)) |
| 250 |
vim.current.buffer[:] = new_buffer_str.split("\n")[:-1] |
| 251 |
for i, j, cursor in cursors: |
| 252 |
window = vim.tabpages[i].windows[j] |
| 253 |
try: |
| 254 |
window.cursor = cursor |
| 255 |
except vim.error: |
| 256 |
window.cursor = (len(window.buffer), 0) |
| 257 |
if not quiet: |
| 258 |
print(f"Black: reformatted in {time.time() - start:.4f}s.") |
| 259 |
|
| 260 |
|
| 261 |
def get_configs(): |
| 262 |
filename = vim.eval("@%") |
| 263 |
path_pyproject_toml = black.find_pyproject_toml((filename,)) |
| 264 |
if path_pyproject_toml: |
| 265 |
toml_config = black.parse_pyproject_toml(path_pyproject_toml) |
| 266 |
else: |
| 267 |
toml_config = {} |
| 268 |
|
| 269 |
return { |
| 270 |
flag.var_name: toml_config.get(flag.name, flag.cast(vim.eval(flag.vim_rc_name))) |
| 271 |
for flag in FLAGS |
| 272 |
} |
| 273 |
|
| 274 |
|
| 275 |
def BlackUpgrade(): |
| 276 |
_initialize_black_env(upgrade=True) |
| 277 |
|
| 278 |
|
| 279 |
def BlackVersion(): |
| 280 |
print(f"Black, version {black.__version__} on Python {sys.version}.") |
| 281 |
EndPython3 |
| 282 |
|
| 283 |
function black#Black(...) |
| 284 |
let kwargs = {} |
| 285 |
for arg in a:000 |
| 286 |
let arg_list = split(arg, '=') |
| 287 |
let kwargs[arg_list[0]] = arg_list[1] |
| 288 |
endfor |
| 289 |
python3 << EOF |
| 290 |
import vim |
| 291 |
|
| 292 |
kwargs = vim.eval("kwargs") |
| 293 |
EOF |
| 294 |
:py3 Black(**kwargs) |
| 295 |
endfunction |
| 296 |
|
| 297 |
function black#BlackUpgrade() |
| 298 |
:py3 BlackUpgrade() |
| 299 |
endfunction |
| 300 |
|
| 301 |
function black#BlackVersion() |
| 302 |
:py3 BlackVersion() |
| 303 |
endfunction |