Skip to content

Commit

Permalink
custom formatting options with black
Browse files Browse the repository at this point in the history
  • Loading branch information
aktech committed Sep 25, 2023
1 parent 288b28e commit 8c2c6d5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
3 changes: 2 additions & 1 deletion lib/python/pyflyby/_cmdline.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ def callback(option, opt_str, value, parser):
group.add_option('--black', action='store_true', default=False,
help=hfmt('''
Use black to format imports. If this option is
used, all other formatting options are ignored.'''))
used, all other formatting options are ignored,
except width'''))
group.add_option('--hanging-indent', type='choice', default='never',
choices=['never','auto','always'],
metavar='never|auto|always',
Expand Down
31 changes: 28 additions & 3 deletions lib/python/pyflyby/_importstmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@


import ast
import subprocess
from collections import namedtuple
from functools import total_ordering

import black

from pyflyby import logger
from pyflyby._flags import CompilerFlags
from pyflyby._format import FormatParams, pyfill
from pyflyby._idents import is_identifier
Expand Down Expand Up @@ -486,11 +490,32 @@ def pretty_print(self, params=FormatParams(),
tokens.append(t)
res = s0 + pyfill(s, tokens, params=params)
if params.use_black:
import black
mode = black.FileMode()
return black.format_str(res, mode=mode)
return self.run_black(res, params)
return res

@staticmethod
def run_black(str_to_format, params):
black_cmd = [
f'black --line-length {str(params.max_line_length)} -c "{str_to_format.strip()}"',
]
try:
completed_process = subprocess.run(
black_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)

if completed_process.returncode == 0:
formatted_code = completed_process.stdout
return formatted_code
else:
logger.info(f"Black command failed: {black_cmd}")
raise ValueError(completed_process.stderr)
except Exception:
raise

@property
def _data(self):
return (self.fromname, self.aliases)
Expand Down

0 comments on commit 8c2c6d5

Please sign in to comment.