From 1e3cb9731661984a019e8d2be8b8e8e386ab4fc4 Mon Sep 17 00:00:00 2001 From: Austin Glaser Date: Tue, 15 Dec 2020 10:44:09 -0800 Subject: [PATCH 1/5] Find pyproject from vim relative to current file --- plugin/black.vim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/black.vim b/plugin/black.vim index c5f0313f4ac..89a1fc0f860 100644 --- a/plugin/black.vim +++ b/plugin/black.vim @@ -193,7 +193,7 @@ def Black(): print(f'Reformatted in {time.time() - start:.4f}s.') def get_configs(): - path_pyproject_toml = black.find_pyproject_toml(vim.eval("fnamemodify(getcwd(), ':t')")) + path_pyproject_toml = black.find_pyproject_toml(vim.eval("@%")) if path_pyproject_toml: toml_config = black.parse_pyproject_toml(path_pyproject_toml) else: From d7f127447e85d895ef7abf3374943bdebc85a4f2 Mon Sep 17 00:00:00 2001 From: Richard Si <63936253+ichard26@users.noreply.github.com> Date: Fri, 11 Jun 2021 22:46:17 -0400 Subject: [PATCH 2/5] Finish and fix this patch (thanks Matt Wozniski!) Both the existing code and the proposed code are broken. The vim.eval() call (whether it's vim.eval("@%") or vim.eval("fnamemodify(getcwd(), ':t')) returns a string, and it passes that string to find_pyproject_toml, which expects a sequence of strings, not a single string, and - since a string is a sequence of single character strings - it gets turned into a list of ridiculous paths. I tested with a file called foo.py, and added a print(path_srcs) into find_project_root, which printed out: [ PosixPath('/home/matt/f'), PosixPath('/home/matt/o'), PosixPath('/home/matt/o'), PosixPath('/home/matt'), PosixPath('/home/matt/p'), PosixPath('/home/matt/y') ] This does work for an unnamed buffer, too - we wind up calling black.find_pyproject_toml(("",)), and that winds up prepending the working directory to any relative paths, so "" just gets turned into the current working directory. Note that find_pyproject_toml needs to be passed a 1-tuple, not a list, because it requires something hashable (thanks to functools.lru_cache being used) Co-authored-by: Matt Wozniski --- autoload/black.vim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/autoload/black.vim b/autoload/black.vim index f0357b07123..0d93aa899d0 100644 --- a/autoload/black.vim +++ b/autoload/black.vim @@ -139,7 +139,8 @@ def Black(): print(f'Reformatted in {time.time() - start:.4f}s.') def get_configs(): - path_pyproject_toml = black.find_pyproject_toml(vim.eval("fnamemodify(getcwd(), ':t')")) + filename = vim.eval("@%") + path_pyproject_toml = black.find_pyproject_toml((filename,)) if path_pyproject_toml: toml_config = black.parse_pyproject_toml(path_pyproject_toml) else: From b56b184d745dde17da029759aee2961d12ed7806 Mon Sep 17 00:00:00 2001 From: Richard Si <63936253+ichard26@users.noreply.github.com> Date: Fri, 11 Jun 2021 22:55:35 -0400 Subject: [PATCH 3/5] I forgot the CHANGELOG entry ... again --- CHANGES.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 02b3fdf75d5..36d0ef67f56 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -12,6 +12,11 @@ - Fix incorrect custom breakpoint indices when string group contains fake f-strings (#2311) +### Integrations + +- The vim plugin now searches the directory containing the current buffer instead of the + current working directory for pyproject.toml. (#1871) + ## 21.5b2 ### _Black_ From a9b9b12437539a4a385326b80abc7cb0947327c0 Mon Sep 17 00:00:00 2001 From: Richard Si <63936253+ichard26@users.noreply.github.com> Date: Fri, 11 Jun 2021 23:01:53 -0400 Subject: [PATCH 4/5] I'm really bad at dealing with merge conflicts sometimes --- plugin/black.vim | 157 ----------------------------------------------- 1 file changed, 157 deletions(-) diff --git a/plugin/black.vim b/plugin/black.vim index d438fae1631..b5edb2a6ade 100644 --- a/plugin/black.vim +++ b/plugin/black.vim @@ -55,163 +55,6 @@ if !exists("g:black_quiet") endif -class Flag(collections.namedtuple("FlagBase", "name, cast")): - @property - def var_name(self): - return self.name.replace("-", "_") - - @property - def vim_rc_name(self): - name = self.var_name - if name == "line_length": - name = name.replace("_", "") - return "g:black_" + name - - -FLAGS = [ - Flag(name="line_length", cast=int), - Flag(name="fast", cast=strtobool), - Flag(name="string_normalization", cast=strtobool), - Flag(name="quiet", cast=strtobool), -] - - -def _get_python_binary(exec_prefix): - try: - default = vim.eval("g:pymode_python").strip() - except vim.error: - default = "" - if default and os.path.exists(default): - return default - if sys.platform[:3] == "win": - return exec_prefix / 'python.exe' - return exec_prefix / 'bin' / 'python3' - -def _get_pip(venv_path): - if sys.platform[:3] == "win": - return venv_path / 'Scripts' / 'pip.exe' - return venv_path / 'bin' / 'pip' - -def _get_virtualenv_site_packages(venv_path, pyver): - if sys.platform[:3] == "win": - return venv_path / 'Lib' / 'site-packages' - return venv_path / 'lib' / f'python{pyver[0]}.{pyver[1]}' / 'site-packages' - -def _initialize_black_env(upgrade=False): - pyver = sys.version_info[:2] - if pyver < (3, 6): - print("Sorry, Black requires Python 3.6+ to run.") - return False - - from pathlib import Path - import subprocess - import venv - virtualenv_path = Path(vim.eval("g:black_virtualenv")).expanduser() - virtualenv_site_packages = str(_get_virtualenv_site_packages(virtualenv_path, pyver)) - first_install = False - if not virtualenv_path.is_dir(): - print('Please wait, one time setup for Black.') - _executable = sys.executable - _base_executable = getattr(sys, "_base_executable", _executable) - try: - executable = str(_get_python_binary(Path(sys.exec_prefix))) - sys.executable = executable - sys._base_executable = executable - print(f'Creating a virtualenv in {virtualenv_path}...') - print('(this path can be customized in .vimrc by setting g:black_virtualenv)') - venv.create(virtualenv_path, with_pip=True) - except Exception: - print('Encountered exception while creating virtualenv (see traceback below).') - print(f'Removing {virtualenv_path}...') - import shutil - shutil.rmtree(virtualenv_path) - raise - finally: - sys.executable = _executable - sys._base_executable = _base_executable - first_install = True - if first_install: - print('Installing Black with pip...') - if upgrade: - print('Upgrading Black with pip...') - if first_install or upgrade: - subprocess.run([str(_get_pip(virtualenv_path)), 'install', '-U', 'black'], stdout=subprocess.PIPE) - print('DONE! You are all set, thanks for waiting ✨ 🍰 ✨') - if first_install: - print('Pro-tip: to upgrade Black in the future, use the :BlackUpgrade command and restart Vim.\n') - if virtualenv_site_packages not in sys.path: - sys.path.insert(0, virtualenv_site_packages) - return True - -if _initialize_black_env(): - import black - import time - -def Black(): - start = time.time() - configs = get_configs() - mode = black.FileMode( - line_length=configs["line_length"], - string_normalization=configs["string_normalization"], - is_pyi=vim.current.buffer.name.endswith('.pyi'), - ) - quiet = configs["quiet"] - - buffer_str = '\n'.join(vim.current.buffer) + '\n' - try: - new_buffer_str = black.format_file_contents( - buffer_str, - fast=configs["fast"], - mode=mode, - ) - except black.NothingChanged: - if not quiet: - print(f'Already well formatted, good job. (took {time.time() - start:.4f}s)') - except Exception as exc: - print(exc) - else: - current_buffer = vim.current.window.buffer - cursors = [] - for i, tabpage in enumerate(vim.tabpages): - if tabpage.valid: - for j, window in enumerate(tabpage.windows): - if window.valid and window.buffer == current_buffer: - cursors.append((i, j, window.cursor)) - vim.current.buffer[:] = new_buffer_str.split('\n')[:-1] - for i, j, cursor in cursors: - window = vim.tabpages[i].windows[j] - try: - window.cursor = cursor - except vim.error: - window.cursor = (len(window.buffer), 0) - if not quiet: - print(f'Reformatted in {time.time() - start:.4f}s.') - -def get_configs(): - path_pyproject_toml = black.find_pyproject_toml(vim.eval("fnamemodify(getcwd(), ':t')")) - if path_pyproject_toml: - toml_config = black.parse_pyproject_toml(path_pyproject_toml) - else: - toml_config = {} - - return { - flag.var_name: flag.cast(toml_config.get(flag.name, vim.eval(flag.vim_rc_name))) - for flag in FLAGS - } - - -def BlackUpgrade(): - _initialize_black_env(upgrade=True) - -def BlackVersion(): - print(f'Black, version {black.__version__} on Python {sys.version}.') - -EndPython3 - -command! Black :py3 Black() -command! BlackUpgrade :py3 BlackUpgrade() -command! BlackVersion :py3 BlackVersion() -======= command! Black :call black#Black() command! BlackUpgrade :call black#BlackUpgrade() command! BlackVersion :call black#BlackVersion() From 2a36254782de65151362340b271967108c4b44b9 Mon Sep 17 00:00:00 2001 From: Richard Si <63936253+ichard26@users.noreply.github.com> Date: Sat, 12 Jun 2021 12:20:08 -0400 Subject: [PATCH 5/5] Be more correct describing search behaviour --- CHANGES.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 36d0ef67f56..90195322ccc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,8 +14,8 @@ ### Integrations -- The vim plugin now searches the directory containing the current buffer instead of the - current working directory for pyproject.toml. (#1871) +- The vim plugin now searches upwards from the directory containing the current buffer + instead of the current working directory for pyproject.toml. (#1871) ## 21.5b2