nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: timothycrosley/isort
Pull request #330 (2015-09-09 06:23:57)

skip files even when file_contents is provided
git hooks provide both file_path and file_contents. Previously,
should_skip only checked if file_path was provided without
file_contents. This introduced a situation where the isort git hook
would fail on files that isort wouldn't touch.

Related PR: https://github.com/timothycrosley/isort/pull/218


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 076ace34..ae234755 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -93,7 +93,7 @@ class SortImports(object):
         self.file_encoding = 'utf-8'
         file_name = file_path
         self.file_path = file_path or ""
-        if file_path and not file_contents:
+        if file_path:
             file_path = os.path.abspath(file_path)
             if self._should_skip(file_path) or self._should_skip_glob(file_path):
                 self.skipped = True
@@ -101,7 +101,7 @@ class SortImports(object):
                     print("WARNING: {0} was skipped as it's listed in 'skip' setting"
                           " or matches a glob in 'skip_glob' setting".format(file_path))
                 file_contents = None
-            else:
+            elif not file_contents:
                 self.file_path = file_path
                 self.file_encoding = coding_check(file_path)
                 with codecs.open(file_path, encoding=self.file_encoding) as file_to_import_sort:


Test patch:
diff --git a/test_isort.py b/test_isort.py
index cd9ea2ef..c0473cc8 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -446,6 +446,16 @@ def test_skip():
                            "import sys  # isort:skip this import needs to be placed here\n")
 
 
+def test_skip_with_file_name():
+    """Ensure skipping a file works even when file_contents is provided."""
+    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
+
+
 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 #346 (2015-09-24 05:17:38)

Feature/fix no sort on two top comments


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f2b5ef85..1ef29082 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,3 +44,4 @@ Changelog
 ### 4.2.2
 - Give an error message when isort is unable to determine where to place a module
 - Allow imports to be sorted by module, independant of import_type, when `force_sort_within_sections` option is set
+- Fixed an issue that caused Python files with 2 top comments not to be sorted
diff --git a/isort/isort.py b/isort/isort.py
index 7323e11e..a29e9868 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -662,11 +662,13 @@ class SortImports(object):
         skip_line = self._in_quote
         if self.index == 1 and line.startswith("#"):
             self._in_top_comment = True
+            return True
         elif self._in_top_comment:
             if not line.startswith("#"):
-               self._in_top_comment = False
-               self._first_comment_index_end = self.index
-        elif '"' in line or "'" in line:
+                self._in_top_comment = False
+                self._first_comment_index_end = self.index
+
+        if '"' in line or "'" in line:
             index = 0
             if self._first_comment_index_start == -1:
                 self._first_comment_index_start = self.index


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 85c513b1..ee9a49ce 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1624,3 +1624,17 @@ def test_sort_within_section():
     test_output = SortImports(file_contents=test_input,force_sort_within_sections=True, order_by_type=False,
                               force_single_line=True).output
     assert test_output == test_input
+
+
+def test_sorting_with_two_top_comments():
+    '''Test to ensure isort will sort files that contain 2 top comments'''
+    test_input = ('#! comment1\n'
+                  "''' comment2\n"
+                  "'''\n"
+                  'import b\n'
+                  'import a\n')
+    assert SortImports(file_contents=test_input).output == ('#! comment1\n'
+                                                            "''' comment2\n"
+                                                            "'''\n"
+                                                            'import a\n'
+                                                            'import b\n')
Repository: timothycrosley/isort
Pull request #387 (2016-01-14 17:27:45)

Add a lines_between_sections setting
Pretty self-explanatory. I'd like to be able to still split imports into sections, but not have a blank line between each section. This seems to do the trick nicely, and would allow people to put more space between sections if they wanted, too. Test included.


Patch:
diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md
index bcf010a5..384fdce9 100644
--- a/ACKNOWLEDGEMENTS.md
+++ b/ACKNOWLEDGEMENTS.md
@@ -61,6 +61,7 @@ Code Contributors
 - Jesse Mullan (@jmullan)
 - Kwok-kuen Cheung (@cheungpat)
 - Johan Bloemberg (@aequitas)
+- Dan Watson (@dcwatson)
 
 Documenters
 ===================
diff --git a/isort/isort.py b/isort/isort.py
index aa2d89f0..150c68c0 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -500,7 +500,7 @@ class SortImports(object):
                         section_comment = "# {0}".format(section_title)
                         if not section_comment in self.out_lines[0:1]:
                             section_output.insert(0, section_comment)
-                    output += section_output + ['']
+                    output += section_output + ([''] * self.config['lines_between_sections'])
 
         while [character.strip() for character in output[-1:]] == [""]:
             output.pop()
diff --git a/isort/settings.py b/isort/settings.py
index ea7b147d..43cdab93 100644
--- a/isort/settings.py
+++ b/isort/settings.py
@@ -89,6 +89,7 @@ default = {'force_to_top': [],
            'order_by_type': True,
            'atomic': False,
            'lines_after_imports': -1,
+           'lines_between_sections': 1,
            'combine_as_imports': False,
            'combine_star': False,
            'include_trailing_comma': False,


Test patch:
diff --git a/test_isort.py b/test_isort.py
index ee9a49ce..06c06ca3 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1638,3 +1638,13 @@ def test_sorting_with_two_top_comments():
                                                             "'''\n"
                                                             'import a\n'
                                                             'import b\n')
+
+
+def test_lines_between_sections():
+    """Test to ensure lines_between_sections works"""
+    test_input = ('from bar import baz\n'
+                  'import os\n')
+    assert SortImports(file_contents=test_input, lines_between_sections=0).output == ('import os\n'
+                                                                                      'from bar import baz\n')
+    assert SortImports(file_contents=test_input, lines_between_sections=2).output == ('import os\n\n\n'
+                                                                                      'from bar import baz\n')
Repository: timothycrosley/isort
Pull request #400 (2016-03-22 18:07:33)

Add support for globbing in forced_separate
Addresses https://github.com/timothycrosley/isort/issues/399

This uses `fnmatch` to provide globbing to the `forced_separate` options. This allows things like "all Django models", for example, to be separated into another section.

The current limitation of this is that it does not apply to local imports. Unfortunately, adding this looks like much more work, so I'm inclined to leave the change at this.


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index cc956eb1..f770fb52 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -36,6 +36,7 @@ import sys
 from collections import namedtuple
 from datetime import datetime
 from difflib import unified_diff
+from fnmatch import fnmatch
 from glob import glob
 from sys import path as PYTHONPATH
 from sys import stdout
@@ -212,7 +213,12 @@ class SortImports(object):
 
         """
         for forced_separate in self.config['forced_separate']:
-            if moduleName.startswith(forced_separate) or moduleName.startswith("." + forced_separate):
+            # Ensure all forced_separate patterns will match to end of string
+            pathGlob = forced_separate
+            if not forced_separate.endswith('*'):
+                pathGlob = '%s*' % forced_separate
+
+            if fnmatch(moduleName, pathGlob) or fnmatch(moduleName, '.' + pathGlob):
                 return forced_separate
 
         if moduleName.startswith("."):


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 06c06ca3..bf794a2e 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1648,3 +1648,25 @@ def test_lines_between_sections():
                                                                                       'from bar import baz\n')
     assert SortImports(file_contents=test_input, lines_between_sections=2).output == ('import os\n\n\n'
                                                                                       'from bar import baz\n')
+
+def test_forced_sepatate_globs():
+    """Test to ensure that forced_separate glob matches lines"""
+    test_input = ('import os\n'
+                  '\n'
+                  'from myproject.foo.models import Foo\n'
+                  '\n'
+                  'from myproject.utils import util_method\n'
+                  '\n'
+                  'from myproject.bar.models import Bar\n'
+                  '\n'
+                  'import sys\n')
+    test_output = SortImports(file_contents=test_input, forced_separate=['*.models'],
+                              line_length=120).output
+
+    assert test_output == ('import os\n'
+                          'import sys\n'
+                          '\n'
+                          'from myproject.utils import util_method\n'
+                          '\n'
+                          'from myproject.bar.models import Bar\n'
+                          'from myproject.foo.models import Foo\n')
Repository: timothycrosley/isort
Pull request #408 (2016-03-28 12:08:00)

Feature/fix issue 375


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6724763b..acd26d2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,3 +45,6 @@ Changelog
 - Give an error message when isort is unable to determine where to place a module
 - Allow imports to be sorted by module, independent of import_type, when `force_sort_within_sections` option is set
 - Fixed an issue that caused Python files with 2 top comments not to be sorted
+
+### 4.2.3
+- Fixed a large number of priority bugs - bug fix only release
diff --git a/isort/isort.py b/isort/isort.py
index 59dbcd01..01051812 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -758,6 +758,7 @@ class SortImports(object):
                             import_string = import_string.rstrip().rstrip("\\") + line.lstrip()
 
                 if import_type == "from":
+                    import_string = import_string.replace("import(", "import (")
                     parts = import_string.split(" import ")
                     from_import = parts[0].split(" ")
                     import_string = " import ".join([from_import[0] + " " + "".join(from_import[1:])] + parts[1:])


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 22a572f5..955efd0d 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1742,3 +1742,12 @@ def test_no_additional_lines_issue_358():
     for attempt in range(5):
         test_output = SortImports(file_contents=test_output, multi_line_output=3, line_length=20).output
         assert test_output == expected_output
+
+
+def test_import_by_paren_issue_375():
+    """Test to ensure isort can correctly handle sorting imports where the paren is directly by the import body"""
+    test_input = ('from .models import(\n'
+                  '   Foo,\n'
+                  '   Bar,\n'
+                  ')\n')
+    assert SortImports(file_contents=test_input).output == 'from .models import Bar, Foo\n'
Repository: timothycrosley/isort
Pull request #450 (2016-07-22 13:35:35)

Use a copy of sys.path
On a 1300 file project at my company, this change reduces the run-time from 11 minutes down to 5 seconds, a 130x improvement.


teeberg: Wooow, for me too :-) From 43 minutes down to 10 seconds. Thank you for this patch! It has some merge conflicts now, could you check those out @oxplot so that we can get this merged? :-)

Patch:
diff --git a/isort/isort.py b/isort/isort.py
index a6c8f81e..17be1afa 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -37,7 +37,6 @@ from datetime import datetime
 from difflib import unified_diff
 from fnmatch import fnmatch
 from glob import glob
-from sys import path as PYTHONPATH
 
 from . import settings
 from .natural import nsorted
@@ -242,7 +241,11 @@ class SortImports(object):
                 if module_name_to_check in self.config.get(config_key, []):
                     return placement
 
-        paths = PYTHONPATH
+        # Use a copy of sys.path to avoid any unintended modifications
+        # to it - e.g. `+=` used below will change paths in place and
+        # if not copied, consequently sys.path, which will grow unbounded
+        # with duplicates on every call to this method.
+        paths = list(sys.path)
         virtual_env = self.config.get('virtual_env') or os.environ.get('VIRTUAL_ENV')
         virtual_env_src = False
         if virtual_env:


Test patch:
diff --git a/test_isort.py b/test_isort.py
index d6b35b61..0559f3d0 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -26,6 +26,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera
 import codecs
 import os
 import shutil
+import sys
 import tempfile
 
 from isort.isort import exists_case_sensitive, SortImports
@@ -1912,3 +1913,17 @@ def test_exists_case_sensitive_directory(tmpdir):
     tmpdir.join('pkg').ensure(dir=1)
     assert exists_case_sensitive(str(tmpdir.join('pkg')))
     assert not exists_case_sensitive(str(tmpdir.join('PKG')))
+
+
+def test_sys_path_mutation():
+    """Test to ensure sys.path is not modified"""
+    try:
+        tmp_dir = tempfile.mkdtemp()
+        os.makedirs(os.path.join(tmp_dir, 'src', 'a'))
+        test_input = "from myproject import test"
+        options = {'virtual_env': tmp_dir}
+        expected_length = len(sys.path)
+        SortImports(file_contents=test_input, **options).output
+        assert len(sys.path) == expected_length
+    finally:
+        shutil.rmtree(tmp_dir, ignore_errors=True)
Repository: timothycrosley/isort
Pull request #467 (2016-09-06 22:42:54)

Fix multiline comments being moved
Fix issue reported here: https://github.com/timothycrosley/isort/issues/460

Multiline comments were being moved into the wrong place.

Test added.

***_Please Note**_*
isort.py  line: 865 was changed in commit: f157b06 and I do not see
why the more complex comparison was needed so it has been removed. Please reread the original commit before accepting this merge request.



Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 01d0f9cc..77df6d49 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -862,8 +862,7 @@ class SortImports(object):
                                    and not 'isort:imports-' in last):
                                 self.comments['above']['straight'].setdefault(module, []).insert(0,
                                                                                                  self.out_lines.pop(-1))
-                                if len(self.out_lines) > max(self.import_index - 1, self._first_comment_index_end,
-                                                             1) - 1:
+                                if len(self.out_lines) > 0:
                                     last = self.out_lines[-1].rstrip()
                                 else:
                                     last = ""


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 52f91a45..03f03fe8 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1767,6 +1767,18 @@ def test_import_by_paren_issue_375():
     assert SortImports(file_contents=test_input).output == 'from .models import Bar, Foo\n'
 
 
+def test_import_by_paren_issue_460():
+    """Test to ensure isort can doesnt move comments around """
+    test_input = """
+# First comment
+# Second comment
+# third comment
+import io
+import os
+"""
+    assert SortImports(file_contents=(test_input)).output == test_input
+
+
 def test_function_with_docstring():
     """Test to ensure isort can correctly sort imports when the first found content is a function with a docstring"""
     add_imports = ['from __future__ import unicode_literals']
Repository: timothycrosley/isort
Pull request #503 (2017-03-20 20:44:33)

Fix smart lines after import section for async functions
With this changes `isort` should properly add default two blank lines after import section when the next line starts with `async def` #453 .



Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 01d0f9cc..16631fb2 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -554,7 +554,7 @@ class SortImports(object):
             if self.config['lines_after_imports'] != -1:
                 self.out_lines[imports_tail:0] = ["" for line in range(self.config['lines_after_imports'])]
             elif next_construct.startswith("def") or next_construct.startswith("class") or \
-               next_construct.startswith("@"):
+               next_construct.startswith("@") or next_construct.startswith("async def"):
                 self.out_lines[imports_tail:0] = ["", ""]
             else:
                 self.out_lines[imports_tail:0] = [""]


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 52f91a45..7b6eee6a 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -919,6 +919,16 @@ def test_smart_lines_after_import_section():
                                                             "def my_function():\n"
                                                             "    pass\n")
 
+    # two spaces if an async method after imports
+    test_input = ("from a import b\n"
+                  "async def my_function():\n"
+                  "    pass\n")
+    assert SortImports(file_contents=test_input).output == ("from a import b\n"
+                                                            "\n"
+                                                            "\n"
+                                                            "async def my_function():\n"
+                                                            "    pass\n")
+
     # two spaces if a method or class after imports - even if comment before function
     test_input = ("from a import b\n"
                   "# comment should be ignored\n"
Repository: timothycrosley/isort
Pull request #518 (2017-05-23 05:32:02)

Feature/fix issue 496


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79ac0dd1..15e25fda 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -70,5 +70,6 @@ Changelog
 - Fixed issue #299: long lines occasionally not wrapped
 - Fixed issue #432: No longer add import inside class when class starts at top of file after encoding comment
 - Fixed issue #440: Added missing `--use-parentheses` option to command line tool and documentation
+- Fixed issue #496: import* imports now get succesfully identified and reformmated instead of deleted
 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 a1f466c2..7ff4cdb2 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -788,7 +788,7 @@ class SortImports(object):
                     self.out_lines.append(line)
                     continue
 
-                line = line.replace("\t", " ")
+                line = line.replace("\t", " ").replace('import*', 'import *')
                 if self.import_index == -1:
                     self.import_index = self.index - 1
 


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 827e3c8f..d240974a 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1961,3 +1961,10 @@ def test_import_inside_class_issue_432():
                        "    def bar(self):\n"
                        "        pass\n")
     assert SortImports(file_contents=test_input, add_imports=['import baz']).output == expected_output
+
+
+def test_wildcard_import_without_space_issue_496():
+    """Test to ensure issue #496: wildcard without space, is resolved"""
+    test_input = 'from findorserver.coupon.models import*'
+    expected_output = 'from findorserver.coupon.models import *\n'
+    assert SortImports(file_contents=test_input).output == expected_output
Repository: timothycrosley/isort
Pull request #519 (2017-05-23 06:41:55)

Feature/fix issue 491


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15e25fda..8f309e03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -70,6 +70,7 @@ Changelog
 - Fixed issue #299: long lines occasionally not wrapped
 - Fixed issue #432: No longer add import inside class when class starts at top of file after encoding comment
 - Fixed issue #440: Added missing `--use-parentheses` option to command line tool and documentation
-- Fixed issue #496: import* imports now get succesfully identified and reformmated instead of deleted
+- 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
 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 7ff4cdb2..ab7a04a7 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -799,7 +799,7 @@ class SortImports(object):
                 if import_type == "from" and len(stripped_line) == 2 and stripped_line[1] != "*" and new_comments:
                     nested_comments[stripped_line[-1]] = comments[0]
 
-                if "(" in line and not self._at_end():
+                if "(" in line.split("#")[0] and not self._at_end():
                     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()


Test patch:
diff --git a/test_isort.py b/test_isort.py
index d240974a..59a9f37a 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1968,3 +1968,21 @@ def test_wildcard_import_without_space_issue_496():
     test_input = 'from findorserver.coupon.models import*'
     expected_output = 'from findorserver.coupon.models import *\n'
     assert SortImports(file_contents=test_input).output == expected_output
+
+
+def test_import_line_mangles_issues_491():
+    """Test to ensure comment on import with parens doesn't cause issues"""
+    test_input = ('import os  # ([\n'
+                  '\n'
+                  'print("hi")\n')
+    assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_import_line_mangles_issues_505():
+    """Test to ensure comment on import with parens doesn't cause issues"""
+    test_input = ('from sys import *  # (\n'
+                  '\n'
+                  '\n'
+                  'def test():\n'
+                  '    print("Test print")\n')
+    assert SortImports(file_contents=test_input).output == test_input