Skip to content

Commit

Permalink
Merge branch 'develop' into issue/1177/colored-output-in-check-mode
Browse files Browse the repository at this point in the history
  • Loading branch information
sztamas committed Jul 27, 2020
2 parents a996689 + 05baa33 commit d0361b0
Show file tree
Hide file tree
Showing 17 changed files with 528 additions and 190 deletions.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Changelog

NOTE: isort follows the [semver](https://semver.org/) versioning standard.

### 5.2.0 TBD
### 5.2.0 July 27, 2020
- Implemented #1335: Official API for diff capturing.
- Implemented #1331: Warn when sections don't match up.
- Implemented #1261: By popular demand, `filter_files` can now be set in the config option.
Expand All @@ -12,9 +12,12 @@ NOTE: isort follows the [semver](https://semver.org/) versioning standard.
- Implemented #970: Support for custom sharable isort profiles.
- Implemented #1214: Added support for git_hook lazy option (Thanks @sztamas!)
- Implemented #941: Added an additional `multi_line_output` mode for more compact formatting (Thanks @sztamas!)
- Implemented #1020: Option for LOCALFOLDER.
- Implemented #1353: Added support for output formatting plugins.
- `# isort: split` can now be used at the end of an import line.
- Fixed #1339: Extra indent is not preserved when isort:skip is used in nested imports.
- Fixed #1348: `--diff` works incorrectly with files that have CRLF line endings.
- Improved code repositories usage of pylint tags (#1350).

### 5.1.4 July 19, 2020
- Fixed issue #1333: Use of wrap_length raises an exception about it not being lower or equal to line_length.
Expand Down
2 changes: 1 addition & 1 deletion docs/contributing/4.-acknowledgements.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ Documenters
- John Villalovos (@JohnVillalovos)
- Kosei Kitahara (@Surgo)
- Marat Sharafutdinov (@decaz)

- Abtin (@abtinmo)

--------------------------------------------

Expand Down
22 changes: 22 additions & 0 deletions example_isort_formatting_plugin/example_isort_formatting_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import black

import isort


def black_format_import_section(
contents: str, extension: str, config: isort.settings.Config
) -> str:
"""Formats the given import section using black."""
if extension.lower() not in ("pyi", "py"):
return contents

try:
return black.format_file_contents(
contents,
fast=True,
mode=black.FileMode(
is_pyi=extension.lower() == "pyi", line_length=config.line_length,
),
)
except black.NothingChanged:
return contents
173 changes: 173 additions & 0 deletions example_isort_formatting_plugin/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions example_isort_formatting_plugin/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[tool.poetry]
name = "example_isort_formatting_plugin"
version = "0.0.1"
description = "An example plugin that modifies isort formatting using black."
authors = ["Timothy Crosley <timothy.crosley@gmail.com>"]
license = "MIT"

[tool.poetry.plugins."isort.formatters"]
example = "example_isort_formatting_plugin:black_format_import_section"

[tool.poetry.dependencies]
python = "^3.6"
isort = "^5.1.4"
black = "^19.10b0"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
2 changes: 1 addition & 1 deletion isort/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "5.1.4"
__version__ = "5.2.0"
8 changes: 8 additions & 0 deletions isort/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,11 @@ def __init__(self, profile: str):
f"Available profiles: {','.join(profiles)}."
)
self.profile = profile


class FormattingPluginDoesNotExist(ISortError):
"""Raised when a formatting plugin is set by the user that doesn't exist"""

def __init__(self, formatter: str):
super().__init__(f"Specified formatting plugin of {formatter} does not exist. ")
self.formatter = formatter
16 changes: 16 additions & 0 deletions isort/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,13 @@ def _build_arg_parser() -> argparse.ArgumentParser:
action="append",
help="Force isort to recognize a module as being part of the current python project.",
)
parser.add_argument(
"--known-local-folder",
dest="known_local_folder",
action="append",
help="Force isort to recognize a module as being a local folder. "
"Generally, this is reserved for relative imports (from . import module).",
)
parser.add_argument(
"-q",
"--quiet",
Expand Down Expand Up @@ -624,6 +631,13 @@ def _build_arg_parser() -> argparse.ArgumentParser:
"Still it can be a great shortcut for collecting imports every once in a while when you put"
" them in the middle of a file.",
)
parser.add_argument(
"--formatter",
dest="formatter",
type=str,
help="Specifies the name of a formatting plugin to use when producing output.",
)

# deprecated options
parser.add_argument(
"--recursive",
Expand Down Expand Up @@ -685,6 +699,8 @@ def _preconvert(item):
return item.name
elif isinstance(item, Path):
return str(item)
elif callable(item) and hasattr(item, "__name__"):
return item.__name__
else:
raise TypeError("Unserializable object {} of type {}".format(item, type(item)))

Expand Down
5 changes: 5 additions & 0 deletions isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@ def sorted_imports(
while output and output[0].strip() == "":
output.pop(0)

if config.formatting_function:
output = config.formatting_function(
parsed.line_separator.join(output), extension, config
).splitlines()

output_at = 0
if parsed.import_index < parsed.original_line_count:
output_at = parsed.import_index
Expand Down
18 changes: 16 additions & 2 deletions isort/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from . import stdlibs
from ._future import dataclass, field
from ._vendored import toml
from .exceptions import InvalidSettingsPath, ProfileDoesNotExist
from .exceptions import FormattingPluginDoesNotExist, InvalidSettingsPath, ProfileDoesNotExist
from .profiles import profiles
from .sections import DEFAULT as SECTION_DEFAULTS
from .sections import FIRSTPARTY, FUTURE, LOCALFOLDER, STDLIB, THIRDPARTY
Expand Down Expand Up @@ -119,6 +119,7 @@ class _Config:
known_future_library: FrozenSet[str] = frozenset(("__future__",))
known_third_party: FrozenSet[str] = frozenset(("google.appengine.api",))
known_first_party: FrozenSet[str] = frozenset()
known_local_folder: FrozenSet[str] = frozenset()
known_standard_library: FrozenSet[str] = frozenset()
extra_standard_library: FrozenSet[str] = frozenset()
known_other: Dict[str, FrozenSet[str]] = field(default_factory=dict)
Expand Down Expand Up @@ -172,6 +173,8 @@ class _Config:
remove_redundant_aliases: bool = False
float_to_top: bool = False
filter_files: bool = False
formatter: str = ""
formatting_function: Optional[Callable[[str, str, object], str]] = None
color_output: bool = False

def __post_init__(self):
Expand Down Expand Up @@ -301,12 +304,13 @@ def __init__(
"known_future_library",
"known_third_party",
"known_first_party",
"known_local_folder",
):
import_heading = key[len(KNOWN_PREFIX) :].lower()
known_other[import_heading] = frozenset(value)
if not import_heading.upper() in combined_config.get("sections", ()):
warn(
f"`{key}` setting is defined, but not {import_heading.upper} is not"
f"`{key}` setting is defined, but not {import_heading.upper()} is not"
" included in `sections` config option:"
f" {combined_config.get('sections', SECTION_DEFAULTS)}."
)
Expand Down Expand Up @@ -347,6 +351,16 @@ def __init__(
path_root / path for path in combined_config.get("src_paths", ())
)

if "formatter" in combined_config:
import pkg_resources

for plugin in pkg_resources.iter_entry_points("isort.formatters"):
if plugin.name == combined_config["formatter"]:
combined_config["formatting_function"] = plugin.load()
break
else:
raise FormattingPluginDoesNotExist(combined_config["formatter"])

# Remove any config values that are used for creating config object but
# aren't defined in dataclass
combined_config.pop("source", None)
Expand Down

0 comments on commit d0361b0

Please sign in to comment.