summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMaxim Kurnikov <maxim.kurnikov@gmail.com>2019-04-26 00:38:31 +0300
committerMaxim Kurnikov <maxim.kurnikov@gmail.com>2019-04-26 00:38:31 +0300
commit61f0dc90524f998d5273b5de6bd1cda6f6401ae6 (patch)
treec8328bf3a26558f81800642cb4380bde8fa56022
parentc8c47b39a65bdb186122aca3b6dc34d2339b913e (diff)
downloadisort-61f0dc90524f998d5273b5de6bd1cda6f6401ae6.tar.gz
extract show_diff, prompt_user
-rw-r--r--isort/format.py31
-rw-r--r--isort/isort.py35
2 files changed, 44 insertions, 22 deletions
diff --git a/isort/format.py b/isort/format.py
index 0c76a143..9aa81bea 100644
--- a/isort/format.py
+++ b/isort/format.py
@@ -1,3 +1,9 @@
+import os
+import sys
+from datetime import datetime
+from difflib import unified_diff
+
+
def format_simplified(import_line: str) -> str:
import_line = import_line.strip()
if import_line.startswith("from "):
@@ -19,3 +25,28 @@ def format_natural(import_line: str) -> str:
return "from {0} import {1}".format(".".join(parts), end)
return import_line
+
+
+def show_unified_diff(*, file_input: str, file_output: str, file_path: str) -> None:
+ unified_diff_lines = unified_diff(
+ file_input.splitlines(keepends=True),
+ file_output.splitlines(keepends=True),
+ fromfile=file_path + ':before',
+ tofile=file_path + ':after',
+ fromfiledate=str(datetime.fromtimestamp(os.path.getmtime(file_path))
+ if file_path else datetime.now()),
+ tofiledate=str(datetime.now())
+ )
+ for line in unified_diff_lines:
+ sys.stdout.write(line)
+
+
+def ask_whether_to_apply_changes_to_file(file_path: str) -> bool:
+ answer = None
+ while answer not in ('yes', 'y', 'no', 'n', 'quit', 'q'):
+ answer = input("Apply suggested changes to '{0}' [y/n/q]? ".format(file_path)).lower()
+ if answer in ('no', 'n'):
+ return False
+ if answer in ('quit', 'q'):
+ sys.exit(1)
+ return True
diff --git a/isort/isort.py b/isort/isort.py
index 84c270c6..10b0744a 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -36,7 +36,7 @@ from difflib import unified_diff
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
from isort import utils
-from isort.format import format_natural, format_simplified
+from isort.format import format_natural, format_simplified, show_unified_diff, ask_whether_to_apply_changes_to_file
from . import settings
from .finders import FindersManager
@@ -160,6 +160,7 @@ class _SortImports(object):
self.out_lines.pop(-1)
self.out_lines.append("")
self.output = self.line_separator.join(self.out_lines)
+
if self.config['atomic']:
try:
out_lines_without_top_comment = self._strip_top_comments(self.out_lines, self.line_separator)
@@ -176,6 +177,7 @@ class _SortImports(object):
print("ERROR: {0} File contains syntax errors.".format(self.file_path))
return
+
if check:
check_output = self.output
check_against = file_contents
@@ -190,23 +192,24 @@ class _SortImports(object):
print("ERROR: {0} Imports are incorrectly sorted.".format(self.file_path))
self.incorrectly_sorted = True
+
if show_diff or self.config['show_diff']:
- self._show_diff(file_contents)
+ show_unified_diff(file_input=file_contents, file_output=self.output,
+ file_path=self.file_path)
+
elif write_to_stdout:
sys.stdout.write(self.output)
+
elif file_name and not check:
if self.output == file_contents:
return
if ask_to_apply:
- self._show_diff(file_contents)
- answer = None
- while answer not in ('yes', 'y', 'no', 'n', 'quit', 'q'):
- answer = input("Apply suggested changes to '{0}' [y/n/q]? ".format(self.file_path)).lower()
- if answer in ('no', 'n'):
- return
- if answer in ('quit', 'q'):
- sys.exit(1)
+ show_unified_diff(file_input=file_contents, file_output=self.output,
+ file_path=self.file_path)
+ apply_changes = ask_whether_to_apply_changes_to_file(self.file_path)
+ if not apply_changes:
+ return
with open(self.file_path, 'w', encoding=self.file_encoding, newline='') as output_file:
if not self.config['quiet']:
@@ -223,18 +226,6 @@ class _SortImports(object):
def correctly_sorted(self) -> bool:
return not self.incorrectly_sorted
- def _show_diff(self, file_contents: str) -> None:
- for line in unified_diff(
- file_contents.splitlines(keepends=True),
- self.output.splitlines(keepends=True),
- fromfile=self.file_path + ':before',
- tofile=self.file_path + ':after',
- fromfiledate=str(datetime.fromtimestamp(os.path.getmtime(self.file_path))
- if self.file_path else datetime.now()),
- tofiledate=str(datetime.now())
- ):
- sys.stdout.write(line)
-
@staticmethod
def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:
"""Strips # comments that exist at the top of the given lines"""