nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: timothycrosley/isort
Pull request #535 (2017-05-31 04:50:15)

Feature/fix issue 436


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ea48d49..6d09727e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ IMPORTANT NOTE: This will be the last release with Python 2.6 support, subsequen
 - Fixed issue #496: import* imports now get successfully identified and reformatted instead of deleted
 - Fixed issue #491: Non ending parentheses withing single line comments no longer cause formatting issues
 - Fixed issue #471: Imports that wrap the maximum line length and contain comments on the last line are no longer rendered incorrectly
+- Fixed issue #436: Force sort within section no longer rearranges comments
 - Fixed issue #484 & #472: Consistent output with imports of same spelling but different case
 Breaking Changes:
     - Fixed issue #511: All command line options with an underscore, have had the underscore replaced with a dash for consistency. This effects: multi-line, add-import, remove-import, force-adds, --force-single-line-imports, and length-sort.
diff --git a/isort/isort.py b/isort/isort.py
index 33af9dec..7f8cc97d 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -536,6 +536,9 @@ class SortImports(object):
 
             if self.config['force_sort_within_sections']:
                 def by_module(line):
+                    if line.startswith('#'):
+                        return '#'
+
                     line = re.sub('^from ', '', line)
                     line = re.sub('^import ', '', line)
                     if not self.config['order_by_type']:


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 26f0a1cd..bb7fd84d 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2083,3 +2083,14 @@ def test_inconsistent_behavior_in_python_2_and_3_issue_479():
     test_input = ('from future.standard_library import hooks\n'
                   'from workalendar.europe import UnitedKingdom\n')
     assert SortImports(file_contents=test_input).output == test_input
+
+def test_sort_within_section_comments_issue_436():
+    """Test to ensure sort within sections leaves comments untouched"""
+    test_input = ('import os.path\n'
+                  'import re\n'
+                  '\n'
+                  '# report.py exists in ... comment line 1\n'
+                  '# this file needs to ...  comment line 2\n'
+                  '# it must not be ...      comment line 3\n'
+                  'import report\n')
+    assert SortImports(file_contents=test_input, force_sort_within_sections=True).output == test_input
Repository: timothycrosley/isort
Pull request #569 (2017-06-07 06:47:15)

Feature/hotfix wrap all modes


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 5ed04944..cecd5af9 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -497,6 +497,8 @@ class SortImports(object):
                 new_import_statement = formatter(import_start, copy.copy(from_imports),
                                                 dynamic_indent, indent, line_length, comments)
                 lines = new_import_statement.split("\n")
+        if import_statement.count('\n') == 0:
+            return self._wrap(import_statement)
         return import_statement
 
     def _add_formatted_imports(self):


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 97f54f6f..0367cfcd 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2136,3 +2136,10 @@ def test_future_below_encoding_issue_545():
                        '\n'
                        'print("hello")\n')
     assert SortImports(file_contents=test_input).output == expected_output
+
+
+def test_long_import_wrap_support_with_mode_2():
+    """Test to ensure mode 2 still allows wrapped imports with slash"""
+    test_input = ('from foobar.foobar.foobar.foobar import \\\n'
+                  '    an_even_longer_function_name_over_80_characters\n')
+    assert SortImports(file_contents=test_input, multi_line_output=2, line_length=80).output == test_input
Repository: timothycrosley/isort
Pull request #588 (2017-08-17 17:52:54)

Set skipped=True when we skip the file
We already do this when the configuration specifies skipping a file, but not when the file is empty or the _file_ specifies skipping.

The "skipped" flag is relied upon by some tooling (I'm not sure if it constitutes public API, but it should be fixed anyway), and that tooling is failing in these cases.


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 865bece5..d9728e41 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -113,6 +113,7 @@ class SortImports(object):
                     file_contents = file_to_import_sort.read()
 
         if file_contents is None or ("isort:" + "skip_file") in file_contents:
+            self.skipped = True
             return
 
         self.in_lines = file_contents.split("\n")


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 7b02933b..2fea1725 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -506,6 +506,15 @@ def test_skip_with_file_name():
     assert skipped
 
 
+def test_skip_within_file():
+    """Ensure skipping a whole file works."""
+    test_input = ("# isort:skip_file\n"
+                  "import django\n"
+                  "import myproject\n")
+
+    assert SortImports(file_contents=test_input, known_third_party=['django']).skipped
+
+
 def test_force_to_top():
     """Ensure forcing a single import to the top of its category works as expected."""
     test_input = ("import lib6\n"
Repository: timothycrosley/isort
Pull request #618 (2017-12-12 04:35:27)

Fix `output` property missing when the input has `isort:skip_file`.
When the input file contains comments `isort:skip_file`, `SortImports` instance doesn't have the `output` property.
This behavior is incompatible with the file-name-based skipping which returns `None`, and could cause `AttributeError`.

I added simply `self.output = None` to fix it.


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 0b12767f..3fc9375b 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -116,6 +116,7 @@ class SortImports(object):
 
         if file_contents is None or ("isort:" + "skip_file") in file_contents:
             self.skipped = True
+            self.output = None
             return
 
         if self.config['line_ending']:


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 7d8ac07f..e5718463 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -501,9 +501,10 @@ def test_skip_with_file_name():
     test_input = ("import django\n"
                   "import myproject\n")
 
-    skipped = SortImports(file_path='/baz.py', file_contents=test_input, known_third_party=['django'],
-                          skip=['baz.py']).skipped
-    assert skipped
+    sort_imports = SortImports(file_path='/baz.py', file_contents=test_input, known_third_party=['django'],
+                               skip=['baz.py'])
+    assert sort_imports.skipped
+    assert sort_imports.output is None
 
 
 def test_skip_within_file():
@@ -511,8 +512,9 @@ def test_skip_within_file():
     test_input = ("# isort:skip_file\n"
                   "import django\n"
                   "import myproject\n")
-
-    assert SortImports(file_contents=test_input, known_third_party=['django']).skipped
+    sort_imports = SortImports(file_contents=test_input, known_third_party=['django'])
+    assert sort_imports.skipped
+    assert sort_imports.output is None
 
 
 def test_force_to_top():
Repository: timothycrosley/isort
Pull request #644 (2018-01-24 23:57:35)

Handle parenthetically enclosed imports starting after an escaped line
Fixes issue #575 


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 96f16f45..ecb2bf24 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -884,6 +884,21 @@ class SortImports(object):
                 else:
                     while line.strip().endswith("\\"):
                         line, comments, new_comments = self._strip_comments(self._get_line(), comments)
+
+                        # Still need to check for parentheses after an escaped line
+                        if "(" in line.split("#")[0] and not self._at_end():
+                            stripped_line = self._strip_syntax(line).strip()
+                            if import_type == "from" and stripped_line and " " not in stripped_line and new_comments:
+                                nested_comments[stripped_line] = comments[-1]
+                            import_string += self.line_separator + line
+
+                            while not line.strip().endswith(")") and not self._at_end():
+                                line, comments, new_comments = self._strip_comments(self._get_line(), comments)
+                                stripped_line = self._strip_syntax(line).strip()
+                                if import_type == "from" and stripped_line and " " not in stripped_line and new_comments:
+                                    nested_comments[stripped_line] = comments[-1]
+                                import_string += self.line_separator + line
+
                         stripped_line = self._strip_syntax(line).strip()
                         if import_type == "from" and stripped_line and " " not in stripped_line and new_comments:
                             nested_comments[stripped_line] = comments[-1]


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 9bcaf4aa..e7dd7b6c 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2317,3 +2317,12 @@ def test_relative_import_of_a_module():
 
     sorted_result = SortImports(file_contents=test_input, force_single_line=True).output
     assert sorted_result == expected_results
+
+
+def test_escaped_parens_sort():
+    test_input = ('from foo import \\ \n'
+                  '(a,\n'
+                  'b,\n'
+                  'c)\n')
+    expected = ('from foo import a, b, c\n')
+    assert SortImports(file_contents=test_input).output == expected
Repository: timothycrosley/isort
Pull request #648 (2018-02-01 06:56:03)

Don't attempt to process files we can't open
If a file does not exist (e.g. a symlink to a file that does not exist yet), don't attempt to sort it.


Patch:
diff --git a/isort/main.py b/isort/main.py
index 653641f5..8c748b20 100755
--- a/isort/main.py
+++ b/isort/main.py
@@ -65,9 +65,13 @@ def is_python_file(path):
     if path.endswith('.py'):
         return True
 
-    with open(path, 'rb') as fp:
-        line = fp.readline(100)
-    return bool(shebang_re.match(line))
+    try:
+        with open(path, 'rb') as fp:
+            line = fp.readline(100)
+    except IOError:
+        return False
+    else:
+        return bool(shebang_re.match(line))
 
 
 class SortAttempt(object):


Test patch:
diff --git a/test_isort.py b/test_isort.py
index e7dd7b6c..db505647 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -30,6 +30,7 @@ import sys
 import tempfile
 
 from isort.isort import SortImports, exists_case_sensitive
+from isort.main import is_python_file
 from isort.settings import WrapModes
 
 SHORT_IMPORT = "from third_party import lib1, lib2, lib3, lib4"
@@ -2326,3 +2327,8 @@ def test_escaped_parens_sort():
                   'c)\n')
     expected = ('from foo import a, b, c\n')
     assert SortImports(file_contents=test_input).output == expected
+
+
+def test_is_python_file_ioerror(tmpdir):
+    does_not_exist = tmpdir.join('fake.txt')
+    assert is_python_file(str(does_not_exist)) is False
Repository: timothycrosley/isort
Pull request #663 (2018-02-03 18:22:29)

Restore fix for issue #651


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index beab947f..0aae5e14 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -634,6 +634,7 @@ class SortImports(object):
                     parts = line.split()
                     if len(parts) >= 3 and parts[1] == '=' and "'" not in parts[0] and '"' not in parts[0]:
                         next_construct = line
+                        break
 
             if self.config['lines_after_imports'] != -1:
                 self.out_lines[imports_tail:0] = ["" for line in range(self.config['lines_after_imports'])]
@@ -821,8 +822,6 @@ class SortImports(object):
                         self._in_quote = line[index]
                 elif line[index] == "#":
                     break
-                elif line[index] not in (' ', '\t'):
-                    break
                 index += 1
 
         return skip_line or self._in_quote or self._in_top_comment


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 56cf85fe..6725464a 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2342,3 +2342,20 @@ def test_escaped_parens_sort():
 def test_is_python_file_ioerror(tmpdir):
     does_not_exist = tmpdir.join('fake.txt')
     assert is_python_file(str(does_not_exist)) is False
+
+
+def test_to_ensure_imports_are_brought_to_top_issue_651():
+    test_input = ('from __future__ import absolute_import, unicode_literals\n'
+                  '\n'
+                  'VAR = """\n'
+                  'multiline text\n'
+                  '"""\n'
+                  '\n'
+                  'from __future__ import unicode_literals\n'
+                  'from __future__ import absolute_import\n')
+    expected_output = ('from __future__ import absolute_import, unicode_literals\n'
+                       '\n'
+                       'VAR = """\n'
+                       'multiline text\n'
+                       '"""\n')
+    assert SortImports(file_contents=test_input).output == expected_output
Repository: timothycrosley/isort
Pull request #664 (2018-02-04 20:04:50)

Feature/fix issue 662


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 0aae5e14..9921958a 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -844,9 +844,9 @@ class SortImports(object):
         self._in_top_comment = False
         while not self._at_end():
             line = self._get_line()
-            line = line.replace("from.import", "from . import")
+            line = line.replace("from.import ", "from . import ")
             line = line.replace("\t", " ").replace('import*', 'import *')
-            line = line.replace(" .import", " . import")
+            line = line.replace(" .import ", " . import ")
             statement_index = self.index
             skip_line = self._skip_line(line)
 


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 6725464a..500060df 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2359,3 +2359,11 @@ def test_to_ensure_imports_are_brought_to_top_issue_651():
                        'multiline text\n'
                        '"""\n')
     assert SortImports(file_contents=test_input).output == expected_output
+
+
+def test_to_ensure_importing_from_imports_module_works_issue_662():
+    test_input = ('@wraps(fun)\n'
+                  'def __inner(*args, **kwargs):\n'
+                  '    from .imports import qualname\n'
+                  '    warn(description=description or qualname(fun), deprecation=deprecation, removal=removal)\n')
+    assert SortImports(file_contents=test_input).output == test_input
Repository: timothycrosley/isort
Pull request #668 (2018-02-06 03:47:49)

Feature/fix issue 665


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 9921958a..1d981eda 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -843,7 +843,7 @@ class SortImports(object):
         self._in_quote = False
         self._in_top_comment = False
         while not self._at_end():
-            line = self._get_line()
+            raw_line = line = self._get_line()
             line = line.replace("from.import ", "from . import ")
             line = line.replace("\t", " ").replace('import*', 'import *')
             line = line.replace(" .import ", " . import ")
@@ -867,7 +867,7 @@ class SortImports(object):
 
             import_type = self._import_type(line)
             if not import_type or skip_line:
-                self.out_lines.append(line)
+                self.out_lines.append(raw_line)
                 continue
 
             for line in (line.strip() for line in line.split(";")):


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 20e2c4a7..205f1f13 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2384,3 +2384,12 @@ def test_to_ensure_no_unexpected_changes_issue_666():
                   'from django.utils.translation import ugettext_lazy as _\n'
                   '"""\n')
     assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_to_ensure_tabs_dont_become_space_issue_665():
+    test_input = ('import os\n'
+                  '\n'
+                  '\n'
+                  'def my_method():\n'
+                  '\tpass\n')
+    assert SortImports(file_contents=test_input).output == test_input
Repository: timothycrosley/isort
Pull request #677 (2018-02-15 18:04:03)

allow for files missing closing newlines in whitespace check
fix for #676


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 3ba3e7d1..1021bd1f 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -187,7 +187,7 @@ class SortImports(object):
                 check_output = check_output.replace(self.line_separator, "").replace(" ", "")
                 check_against = check_against.replace(self.line_separator, "").replace(" ", "")
 
-            if check_output == check_against:
+            if check_output.strip() == check_against.strip():
                 if self.config['verbose']:
                     print("SUCCESS: {0} Everything Looks Good!".format(self.file_path))
                 return


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 8c5f275c..25077bd5 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2111,6 +2111,17 @@ def test_strict_whitespace_by_default(capsys):
     assert out == 'ERROR:  Imports are incorrectly sorted.\n'
 
 
+def test_strict_whitespace_no_closing_newline_issue_676(capsys):
+    test_input = ('import os\n'
+                  '\n'
+                  'from django.conf import settings\n'
+                  '\n'
+                  'print(1)')
+    SortImports(file_contents=test_input, check=True)
+    out, err = capsys.readouterr()
+    assert out == ''
+
+
 def test_ignore_whitespace(capsys):
     test_input = ('import os\n'
                   'from django.conf import settings\n')
Repository: timothycrosley/isort
Pull request #734 (2018-08-13 07:13:55)

Make formatting import compatible with black check
When the very long line is met isort should wrap import into one of
multi line outputs. Black says that vertical hanging indent should be
choosen. An for most cases it works correctly. But when only one
import is on the list there is some difference.
Black suggests that there shouldn't be a trailing comma which isort is
giving.


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index e3594716..8b1d681f 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -742,13 +742,17 @@ class SortImports(object):
         return statement
 
     def _output_vertical_hanging_indent(self, statement, imports, white_space, indent, line_length, comments):
+        trailing = ""
+        if len(imports) > 1 and self.config['include_trailing_comma']:
+            trailing = ','
+
         return "{0}({1}{2}{3}{4}{5}{2})".format(
             statement,
             self._add_comments(comments),
             self.line_separator,
             indent,
             ("," + self.line_separator + indent).join(imports),
-            "," if self.config['include_trailing_comma'] else "",
+            trailing,
          )
 
     def _output_vertical_grid_common(self, statement, imports, white_space, indent, line_length, comments,


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 0bffe9f1..330d4d95 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1272,7 +1272,7 @@ def test_include_trailing_comma():
     ).output
     assert test_output_wrap_single_import_vertical_indent == (
         "from third_party import (\n"
-        "    lib1,\n"
+        "    lib1\n"
         ")\n"
     )
Repository: timothycrosley/isort
Pull request #820 (2019-02-23 23:14:08)

Feature/fix issue 577
Fixes Issue #577 & Issue #417 


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index df075bc2..c15b3cb0 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -255,6 +255,14 @@ class SortImports(object):
 
     @staticmethod
     def _module_key(module_name, config, sub_imports=False, ignore_case=False, section_name=None):
+        dots = 0
+        while module_name.startswith('.'):
+            dots += 1
+            module_name = module_name[1:]
+
+        if dots:
+            module_name = '{} {}'.format(('.' * dots), module_name)
+
         prefix = ""
         if ignore_case:
             module_name = str(module_name).lower()


Test patch:
diff --git a/test_isort.py b/test_isort.py
index bdd4453c..e2320295 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2715,3 +2715,19 @@ def test_comments_not_removed_issue_576():
                   '# this comment is important and should not be removed\n'
                   'from sys import api_version as api_version\n')
     assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_inconsistent_relative_imports_issue_577():
+    test_input = ('from . import ipsum\n'
+                  'from . import lorem\n'
+                  'from .dolor import consecteur\n'
+                  'from .sit import apidiscing\n'
+                  'from .. import donec\n'
+                  'from .. import euismod\n'
+                  'from ..mi import iaculis\n'
+                  'from ..nec import tempor\n'
+                  'from ... import diam\n'
+                  'from ... import dui\n'
+                  'from ...eu import dignissim\n'
+                  'from ...ex import metus\n')
+    assert SortImports(file_contents=test_input, force_single_line=True).output == test_input
Repository: timothycrosley/isort
Pull request #823 (2019-02-24 16:52:53)

Fix issue #762


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index c15b3cb0..697cc7a7 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -854,7 +854,6 @@ class SortImports(object):
 
                 if self.import_index == -1:
                     self.import_index = self.index - 1
-
                 nested_comments = {}
                 import_string, comments, new_comments = self._strip_comments(line)
                 stripped_line = [part for part in self._strip_syntax(import_string).strip().split(" ") if part]
@@ -873,7 +872,7 @@ class SortImports(object):
                         line, comments, new_comments = self._strip_comments(self._get_line(), comments)
 
                         # Still need to check for parentheses after an escaped line
-                        if "(" in line.split("#")[0] and not self._at_end():
+                        if "(" in line.split("#")[0] and ")" not in line.split("#")[0] and not self._at_end():
                             stripped_line = self._strip_syntax(line).strip()
                             if import_type == "from" and stripped_line and " " not in stripped_line and new_comments:
                                 nested_comments[stripped_line] = comments[-1]


Test patch:
diff --git a/test_isort.py b/test_isort.py
index aafafceb..19fb0540 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2742,3 +2742,13 @@ def test_inconsistent_relative_imports_issue_577():
                   'from ...eu import dignissim\n'
                   'from ...ex import metus\n')
     assert SortImports(file_contents=test_input, force_single_line=True).output == test_input
+
+
+def test_unwrap_issue_762():
+    test_input = ('from os.path \\\n'
+                  'import (join, split)\n')
+    assert SortImports(file_contents=test_input).output == 'from os.path import join, split\n'
+
+    test_input = ('from os.\\\n'
+                  '    path import (join, split)')
+    assert SortImports(file_contents=test_input).output == 'from os.path import join, split\n'