def main(args): """ This matches the default behaviour of the black formatter. This script will raise an exception if changes by black are required. """ sources = set() root = Path(os.getcwd()) p = Path(".") include_regex = re_compile_maybe_verbose(DEFAULT_INCLUDES) exclude_regex = re_compile_maybe_verbose(DEFAULT_EXCLUDES) report = Report() sources.update( gen_python_files_in_dir(p, root, include_regex, exclude_regex, report, get_gitignore(root))) # To conform to flake8 line length used for this project. mode = FileMode(line_length=79) write_back = WriteBack.from_configuration(check=False, diff=not args.force) reformat_many( sources=sources, fast=False, write_back=write_back, mode=mode, report=report, ) if report.change_count != 0: exception_msg = """ Black formatter suggests formatting changes required Run with '-f' option to automatically format. """ raise Exception(exception_msg)
def main( ctx: click.Context, code: Optional[str], line_length: int, target_version: List[TargetVersion], check: bool, diff: bool, fast: bool, pyi: bool, py36: bool, skip_string_normalization: bool, single_quotes: bool, quiet: bool, verbose: bool, include: str, exclude: str, src: Tuple[str], config: Optional[str], ) -> None: """The uncompromising code formatter.""" write_back = WriteBack.from_configuration(check=check, diff=diff) if target_version: if py36: err('Cannot use both --target-version and --py36') ctx.exit(2) else: versions = set(target_version) elif py36: err('--py36 is deprecated and will be removed in a future version. ' 'Use --target-version py36 instead.') versions = PY36_VERSIONS else: # We'll autodetect later. versions = set() mode = FileMode( target_versions=versions, line_length=line_length, is_pyi=pyi, string_normalization=not skip_string_normalization, ) if single_quotes: black.normalize_string_quotes = patched_normalize_string_quotes if config and verbose: out(f'Using configuration from {config}.', bold=False, fg='blue') if code is not None: print(format_str(code, mode=mode)) ctx.exit(0) try: include_regex = re_compile_maybe_verbose(include) except re.error: err(f'Invalid regular expression for include given: {include!r}') ctx.exit(2) try: exclude_regex = re_compile_maybe_verbose(exclude) except re.error: err(f'Invalid regular expression for exclude given: {exclude!r}') ctx.exit(2) report = Report(check=check, quiet=quiet, verbose=verbose) root = find_project_root(src) sources: Set[Path] = set() path_empty(src=src, quiet=quiet, verbose=verbose, ctx=ctx, msg=None) for s in src: p = Path(s) if p.is_dir(): sources.update( gen_python_files_in_dir( p, root, include_regex, exclude_regex, report, get_gitignore(root), )) elif p.is_file() or s == '-': # if a file was explicitly given, we don't care about its extension sources.add(p) else: err(f'invalid path: {s}') if len(sources) == 0: if verbose or not quiet: out('No Python files are present to be formatted. Nothing to do 😴') ctx.exit(0) reformat_many( sources=sources, fast=fast, write_back=write_back, mode=mode, report=report, ) if verbose or not quiet: out('Oh no! 💥 💔 💥' if report.return_code else 'All done! ✨ 🍰 ✨') click.secho(str(report), err=True) ctx.exit(report.return_code)
def cli( ctx: click.Context, line_length: int, check: bool, include: str, exclude: str, quiet: bool, verbose: bool, clear_output: bool, src: Tuple[str], config: Optional[str], ) -> None: """ The uncompromising code formatter, for Jupyter notebooks. """ write_back = black.WriteBack.from_configuration(check=check, diff=False) mode = black.FileMode.from_configuration( py36=True, pyi=False, skip_string_normalization=False, skip_numeric_underscore_normalization=False, ) if config and verbose: black.out(f"Using configuration from {config}.", bold=False, fg="blue") try: include_regex = black.re_compile_maybe_verbose(include) except re.error: black.err(f"Invalid regular expression for include given: {include!r}") ctx.exit(2) try: exclude_regex = black.re_compile_maybe_verbose(exclude) except re.error: black.err(f"Invalid regular expression for exclude given: {exclude!r}") ctx.exit(2) report = black.Report(check=check, quiet=quiet, verbose=verbose) root = black.find_project_root(src) sources: Set[Path] = set() for s in src: p = Path(s) if p.is_dir(): sources.update( black.gen_python_files_in_dir( p, root, include_regex, exclude_regex, report ) ) elif p.is_file() or s == "-": # if a file was explicitly given, we don't care about its extension sources.add(p) else: black.err(f"invalid path: {s}") if len(sources) == 0: if verbose or not quiet: black.out("No paths given. Nothing to do.") ctx.exit(0) for source in sources: reformat_one( src=source, line_length=line_length, write_back=write_back, mode=mode, clear_output=clear_output, report=report, quiet=quiet, verbose=verbose, ) if verbose or not quiet: black.out(f"All done!") click.secho(str(report), err=True) ctx.exit(report.return_code)
async def api( *, src: Iterable[str], work_dir: str, line_length: int = black.DEFAULT_LINE_LENGTH, check: bool = False, diff: bool = False, fast: bool = False, pyi: bool = False, py36: bool = False, skip_string_normalization: bool = False, quiet: bool = False, verbose: bool = False, include: str = black.DEFAULT_INCLUDES, exclude: str = black.DEFAULT_EXCLUDES, config: Optional[str] = None, ) -> int: """The uncompromising code formatter.""" src = tuple(src) work_dir = Path(work_dir) loop = asyncio.get_event_loop() write_back = black.WriteBack.from_configuration(check=check, diff=diff) mode = black.FileMode.from_configuration( py36=py36, pyi=pyi, skip_string_normalization=skip_string_normalization ) if config and verbose: black.out(f"Using configuration from {config}.", bold=False, fg="blue") try: include_regex = black.re_compile_maybe_verbose(include) except re.error: black.err(f"Invalid regular expression for include given: {include!r}") return 2 try: exclude_regex = black.re_compile_maybe_verbose(exclude) except re.error: black.err(f"Invalid regular expression for exclude given: {exclude!r}") return 2 report = black.Report(check=check, quiet=quiet, verbose=verbose) root = black.find_project_root((work_dir,)) sources: Set[Path] = set() for s in src: p = work_dir / Path(s) if p.is_dir(): sources.update( black.gen_python_files_in_dir( p, root, include_regex, exclude_regex, report ) ) elif p.is_file() or s == "-": # if a file was explicitly given, we don't care about its extension sources.add(p) else: black.err(f"invalid path: {s}") if len(sources) == 0: if verbose or not quiet: black.out("No paths given. Nothing to do 😴") return 0 if len(sources) == 1: black.reformat_one( src=sources.pop(), line_length=line_length, fast=fast, write_back=write_back, mode=mode, report=report, ) else: await black.schedule_formatting( sources=sources, line_length=line_length, fast=fast, write_back=write_back, mode=mode, report=report, executor=PROCESS_POOL, loop=loop, ) if verbose or not quiet: bang = "💥 💔 💥" if report.return_code else "✨ 🍰 ✨" black.out(f"All done! {bang}") black.secho(str(report), err=True) return report.return_code
def process(args): if not args.src: print("No Path provided. Nothing to do 😴") return 0 selected_formats = getattr(args, "formats", None) if selected_formats: formats.disable( set(formats.detection_funcs.keys()) - set(selected_formats) - set(["none"])) disabled_formats = getattr(args, "disable_formats", None) if disabled_formats: formats.disable(disabled_formats) try: include_regex = black.re_compile_maybe_verbose(args.include) except black.re.error: print( f"Invalid regular expression for include given: {args.include!r}", file=sys.stderr, ) return 2 try: exclude_regex = black.re_compile_maybe_verbose(args.exclude) except black.re.error: print( f"Invalid regular expression for exclude given: {args.exclude!r}", file=sys.stderr, ) return 2 sources = set(collect_files(args.src, include_regex, exclude_regex)) if len(sources) == 0: print("No files are present to be formatted. Nothing to do 😴") return 0 target_versions = set(black.TargetVersion[version.upper()] for version in getattr(args, "target_versions", ())) mode = black.FileMode( line_length=args.line_length, target_versions=target_versions, ) actions = { "inplace": format_and_overwrite, "check": format_and_check, } action = actions.get(args.action) changed_sources = {source: action(source, mode) for source in sources} n_reformatted, n_unchanged, n_error = statistics(changed_sources) report_formatters = { "inplace": report_changes, "check": report_possible_changes, } report = report_formatters.get(args.action)(n_reformatted, n_unchanged, n_error) if n_error > 0: return_code = 123 elif args.action == "check" and n_reformatted > 0: return_code = 1 else: return_code = 0 print("Oh no! 💥 💔 💥" if return_code else "All done! ✨ 🍰 ✨") print(report) return return_code