nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: microsoft/qsharp
Pull request #509 (2023-07-27 16:42:58)

Include core package in incremental compilation
This fixes an oversight where the incremental compiler did not include the core library in the set of globals, meaning callables like `Length` were not available. Also adds a test to confirm availability of those callables.


Patch:
diff --git a/compiler/qsc_frontend/src/incremental.rs b/compiler/qsc_frontend/src/incremental.rs
index c9e6695d..2bc93322 100644
--- a/compiler/qsc_frontend/src/incremental.rs
+++ b/compiler/qsc_frontend/src/incremental.rs
@@ -51,6 +51,11 @@ impl Compiler {
     pub fn new(store: &PackageStore, dependencies: impl IntoIterator<Item = PackageId>) -> Self {
         let mut resolve_globals = resolve::GlobalTable::new();
         let mut typeck_globals = typeck::GlobalTable::new();
+        if let Some(unit) = store.get(PackageId::CORE) {
+            resolve_globals.add_external_package(PackageId::CORE, &unit.package);
+            typeck_globals.add_external_package(PackageId::CORE, &unit.package);
+        }
+
         for id in dependencies {
             let unit = store
                 .get(id)


Test patch:
diff --git a/compiler/qsc/src/interpret/stateful/tests.rs b/compiler/qsc/src/interpret/stateful/tests.rs
index 1fc16180..7622808d 100644
--- a/compiler/qsc/src/interpret/stateful/tests.rs
+++ b/compiler/qsc/src/interpret/stateful/tests.rs
@@ -39,6 +39,13 @@ mod given_interpreter {
             is_unit_with_output(&result, &output, "_");
         }
 
+        #[test]
+        fn core_members_should_be_available() {
+            let mut interpreter = get_interpreter();
+            let (result, output) = line(&mut interpreter, "Length([1, 2, 3])");
+            is_only_value(&result, &output, &Value::Int(3));
+        }
+
         #[test]
         fn let_bindings_update_interpreter() {
             let mut interpreter = get_interpreter();
Repository: timothycrosley/isort
Pull request #236 (2015-02-05 03:28:35)

Timgraham 224


Patch:
diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md
index 28690ec9..c2814401 100644
--- a/ACKNOWLEDGEMENTS.md
+++ b/ACKNOWLEDGEMENTS.md
@@ -39,6 +39,7 @@ Code Contributors
 - Kasper Jacobsen (@dinoshauer)
 - Sebastian Pipping (@hartwork)
 - Helen Sherwood-Taylor (@helenst)
+- Mocker (@Zuckonit)
 - Tim Graham (@timgraham)
 
 Documenters
diff --git a/isort/isort.py b/isort/isort.py
index beb36bc5..8fafd9d0 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -594,8 +594,13 @@ class SortImports(object):
 
     def _strip_syntax(self, import_string):
         import_string = import_string.replace("_import", "[[i]]")
-        for remove_syntax in ['\\', '(', ')', ",", 'from ', 'import ']:
+        for remove_syntax in ['\\', '(', ')', ',']:
             import_string = import_string.replace(remove_syntax, " ")
+        import_list = import_string.split()
+        for key in ('from', 'import'):
+            if key in import_list:
+                import_list.remove(key)
+        import_string = ' '.join(import_list)
         import_string = import_string.replace("[[i]]", "_import")
         return import_string
 


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 180c506f..7fde1b43 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1181,3 +1181,16 @@ def test_sticky_comments():
                   "# Used for type-hinting (ref: https://github.com/davidhalter/jedi/issues/414).\n"
                   "from selenium.webdriver.remote.webdriver import WebDriver  # noqa\n")
     assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_zipimport():
+    """Imports ending in "import" shouldn't be clobbered"""
+    test_input = "from zipimport import zipimport\n"
+    assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_from_ending():
+    """Imports ending in "from" shouldn't be clobbered."""
+    test_input = "from foo import get_foo_from, get_foo\n"
+    expected_output = "from foo import get_foo, get_foo_from\n"
+    assert SortImports(file_contents=test_input).output == expected_output
Repository: timothycrosley/isort
Pull request #240 (2015-02-05 17:01:09)

Feature/fix issue 238


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 038cd3d0..114daf07 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -706,7 +706,8 @@ class SortImports(object):
                     if comments:
                         self.comments['from'].setdefault(import_from, []).extend(comments)
                     last = self.out_lines and self.out_lines[-1].rstrip() or ""
-                    if last.startswith("#") and not last.endswith('"""') and not last.endswith("'''"):
+                    if (len(self.out_lines) > self.import_index and last.startswith("#") and not last.endswith('"""') and not
+                        last.endswith("'''")):
                         self.comments['above']['from'].setdefault(import_from, []).append(self.out_lines.pop(-1))
                     if root.get(import_from, False):
                         root[import_from].update(imports)
@@ -718,6 +719,7 @@ class SortImports(object):
                             self.comments['straight'][module] = comments
                             comments = None
                         last = self.out_lines and self.out_lines[-1].rstrip() or ""
-                        if last.startswith("#") and not last.endswith('"""') and not last.endswith("'''"):
+                        if (len(self.out_lines) > self.import_index and last.startswith("#") and not
+                            last.endswith('"""') and not last.endswith("'''")):
                             self.comments['above']['from'][module] = self.out_lines.pop(-1)
                         self.imports[self.place_module(module)][import_type].add(module)


Test patch:
diff --git a/test_isort.py b/test_isort.py
index f25ae5fb..96896288 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1201,3 +1201,16 @@ def test_from_first():
     test_input = "from os import path\nimport os\n"
     assert SortImports(file_contents=test_input, from_first=True).output == test_input
 
+
+def test_top_comments():
+    """Ensure correct behavior with top comments"""
+    test_input = ("# -*- encoding: utf-8 -*-\n"
+                  "# Test comment\n"
+                  "#\n"
+                  "from __future__ import unicode_literals\n")
+    assert SortImports(file_contents=test_input).output == test_input
+
+    test_input = ("# -*- coding: utf-8 -*-\n"
+                  "from django.db import models\n"
+                  "from django.utils.encoding import python_2_unicode_compatible\n")
+    assert SortImports(file_contents=test_input).output == test_input
Repository: timothycrosley/isort
Pull request #256 (2015-02-15 23:05:45)

force_grid_wrap code and setting had different names
now they match!


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 13dc6d44..3edba3a1 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -380,11 +380,9 @@ class SortImports(object):
                         import_statement = self._add_comments(comments, import_start + (", ").join(from_imports))
                     if not from_imports:
                         import_statement = ""
-                    if len(import_statement) > self.config['line_length']:
-                        import_statement = self._wrap(import_statement)
                     if len(from_imports) > 1 and (
                         len(import_statement) > self.config['line_length']
-                        or self.config.get('force_from_wrap')
+                        or self.config.get('force_grid_wrap')
                     ):
                         output_mode = settings.WrapModes._fields[self.config.get('multi_line_output',
                                                                                     0)].lower()
@@ -409,6 +407,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")
+                    elif len(import_statement) > self.config['line_length']:
+                        import_statement = self._wrap(import_statement)
 
                 if import_statement:
                     above_comments = self.comments['above']['from'].get(module, None)


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 457b9ef2..2c354147 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1264,17 +1264,40 @@ def test_consistency():
 
 def test_force_grid_wrap():
     """Ensures removing imports works as expected."""
-    test_input = ("from foo import lib6, lib7\n"
-                  "from bar import lib2\n")
+    test_input = (
+      "from foo import lib6, lib7\n"
+      "from bar import lib2\n"
+    )
     test_output = SortImports(
       file_contents=test_input,
-      force_from_wrap=True,
+      force_grid_wrap=True,
       multi_line_output=WrapModes.VERTICAL_HANGING_INDENT
       ).output
-    print(test_output)
     assert test_output == """from bar import lib2
 from foo import (
     lib6,
     lib7
 )
 """
+
+def test_force_grid_wrap_long():
+    """Ensure that force grid wrap still happens with long line length"""
+    test_input = (
+      "from foo import lib6, lib7\n"
+      "from bar import lib2\n"
+      "from babar import something_that_is_kind_of_long"
+    )
+    test_output = SortImports(
+      file_contents=test_input,
+      force_grid_wrap=True,
+      multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
+      line_length=9999,
+      ).output
+    print(test_output)
+    assert test_output == """from babar import something_that_is_kind_of_long
+from bar import lib2
+from foo import (
+    lib6,
+    lib7
+)
+"""
Repository: timothycrosley/isort
Pull request #257 (2015-02-19 06:34:43)

Feature/fix issue 250


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 3edba3a1..b0a740a0 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -627,7 +627,7 @@ class SortImports(object):
                 import_list.remove(key)
         import_string = ' '.join(import_list)
         import_string = import_string.replace("[[i]]", "_import")
-        return import_string
+        return import_string.replace("{ ", "{|").replace(" }", "|}")
 
     def _parse(self):
         """Parses a python file taking out and categorizing imports."""
@@ -696,7 +696,8 @@ class SortImports(object):
                     from_import = parts[0].split(" ")
                     import_string = " import ".join([from_import[0] + " " + "".join(from_import[1:])] + parts[1:])
 
-                imports = self._strip_syntax(import_string).split()
+                imports = [item.replace("{|", "{ ").replace("|}", " }") for item in
+                           self._strip_syntax(import_string).split()]
                 if "as" in imports and (imports.index('as') + 1) < len(imports):
                     while "as" in imports:
                         index = imports.index('as')


Test patch:
diff --git a/test_isort.py b/test_isort.py
index a26f8cc6..5ca0d67d 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1300,3 +1300,23 @@ from foo import (
     lib7
 )
 """
+
+
+def test_uses_jinja_variables():
+    """Test a basic set of imports that use jinja variables"""
+    test_input = ("import sys\n"
+                  "import os\n"
+                  "import myproject.{ test }\n"
+                  "import django.{ settings }")
+    test_output = SortImports(file_contents=test_input, known_third_party=['django'],
+                              known_first_party=['myproject']).output
+    assert test_output == ("import os\n"
+                           "import sys\n"
+                           "\n"
+                           "import django.{ settings }\n"
+                           "\n"
+                           "import myproject.{ test }\n")
+
+    test_input = ("import {{ cookiecutter.repo_name }}\n"
+                  "from foo import {{ cookiecutter.bar }}\n")
+    assert SortImports(file_contents=test_input).output == test_input
Repository: timothycrosley/isort
Pull request #264 (2015-03-31 20:21:43)

Implement `use_parentheses`.
Instead of using the `\` as line continuation allow wrapping the the long line within parentheses as suggested in PEP8 using a config setting.

Note that I'm not sure if I've implemented this correctly, but it seems to work :-)


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index b0a740a0..9a9a9e15 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -293,8 +293,11 @@ class SortImports(object):
                         line = splitter.join(line_parts)
                     if not line:
                         line = next_line.pop()
-                    return "{0}{1} \\\n{2}".format(line, splitter,
-                                                  self._wrap(self.config['indent'] + splitter.join(next_line).lstrip()))
+
+                    cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip())
+                    if self.config['use_parentheses']:
+                        return "{0}{1} (\n{2})".format(line, splitter, cont_line)
+                    return "{0}{1} \\\n{2}".format(line, splitter, cont_line)
 
         return line
 
diff --git a/isort/settings.py b/isort/settings.py
index 230636ca..ff103eda 100644
--- a/isort/settings.py
+++ b/isort/settings.py
@@ -82,6 +82,7 @@ default = {'force_to_top': [],
            'import_heading_firstparty': '',
            'import_heading_localfolder': '',
            'balanced_wrapping': False,
+           'use_parentheses': False,
            'order_by_type': True,
            'atomic': False,
            'lines_after_imports': -1,


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 5ca0d67d..3da01ba0 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -413,6 +413,18 @@ def test_custom_indent():
                            "  lib20, lib21, lib22\n")
 
 
+def test_use_parentheses():
+    test_input = (
+        "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import \\"
+        "    my_custom_function as my_special_function"
+    )
+    test_output = SortImports(
+        file_contents=test_input, known_third_party=['django'],
+        line_length=79, use_parentheses=True,
+    ).output
+    assert '(' in test_output
+
+
 def test_skip():
     """Ensure skipping a single import will work as expected."""
     test_input = ("import myproject\n"
Repository: timothycrosley/isort
Pull request #266 (2015-04-15 23:50:10)

Feature/fix issue 265


Patch:
diff --git a/isort/settings.py b/isort/settings.py
index 230636ca..9bfdbc2d 100644
--- a/isort/settings.py
+++ b/isort/settings.py
@@ -65,7 +65,7 @@ default = {'force_to_top': [],
                                       "timeit", "trace", "traceback", "unittest", "urllib", "urllib2", "urlparse",
                                       "usercustomize", "uuid", "warnings", "weakref", "webbrowser", "whichdb", "xml",
                                       "xmlrpclib", "zipfile", "zipimport", "zlib", 'builtins', '__builtin__', 'thread',
-                                      "binascii", "statistics", "unicodedata"],
+                                      "binascii", "statistics", "unicodedata", "fcntl"],
            'known_third_party': ['google.appengine.api'],
            'known_first_party': [],
            'multi_line_output': WrapModes.GRID,


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 5ca0d67d..d8467498 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1320,3 +1320,12 @@ def test_uses_jinja_variables():
     test_input = ("import {{ cookiecutter.repo_name }}\n"
                   "from foo import {{ cookiecutter.bar }}\n")
     assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_fcntl():
+    """Test to ensure fcntl gets correctly recognized as stdlib import"""
+    test_input = ("import fcntl\n"
+                  "import os\n"
+                  "import sys\n")
+    assert SortImports(file_contents=test_input).output == test_input
+
Repository: timothycrosley/isort
Pull request #281 (2015-06-10 19:32:44)

Fix Import Line Splitting Bug
Hi Timothy!

Thanks for creating isort! It's quite useful.

I ran into a bug when using isort to lint a file that contained an import in which the split token "import" appeared in a module's name. This resulted in the module's name being split into non-sense strings.

e.g.
```python
from mycompany.model.size_value_array_import_func import (
    get_size_value_array_import_func_jobs,
)
```
... was split into ...
```python
[u'mycompany.model.size_value_array_', u'_func ', u' get_size_value_array_', u'_func_jobs']
```
I have patched the isort _wrap() function to prevent this from happening. I ensured that all tests passed after my patch was introduced, and I added an additional test to ensure that line splitting is word boundary aware.

All the best,

-Patrick



Patch:
diff --git a/isort/isort.py b/isort/isort.py
index b838b3e4..e5c2ff68 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -30,6 +30,7 @@ import codecs
 import copy
 import itertools
 import os
+import re
 from collections import namedtuple
 from datetime import datetime
 from difflib import unified_diff
@@ -287,8 +288,9 @@ class SortImports(object):
         """
         if len(line) > self.config['line_length']:
             for splitter in ("import", "."):
-                if splitter in line and not line.strip().startswith(splitter):
-                    line_parts = line.split(splitter)
+                exp = r"\b" + re.escape(splitter) + r"\b"
+                if re.search(exp, line) and not line.strip().startswith(splitter):
+                    line_parts = re.split(exp, line)
                     next_line = []
                     while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts:
                         next_line.append(line_parts.pop())


Test patch:
diff --git a/runtests.py b/runtests.py
index ad902463..a024d3d5 100644
--- a/runtests.py
+++ b/runtests.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#!/usr/bin/env python
 
 sources = """
 eNrcvWmXG1l2INYzY1tjeGYk2ePtg32iQVGIKCKDSXZpyylUqVRFqqmuYvFwUVPOSoGRQGRmNJER
diff --git a/test_isort.py b/test_isort.py
index d8467498..9ba1a3c4 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1329,3 +1329,14 @@ def test_fcntl():
                   "import sys\n")
     assert SortImports(file_contents=test_input).output == test_input
 
+def test_import_split_is_word_boundary_aware():
+
+    test_input = ("from mycompany.model.size_value_array_import_func import ("
+                "    get_size_value_array_import_func_jobs,"
+                ")")
+    test_output = SortImports(file_contents=test_input,
+      multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
+      line_length=79).output
+
+    assert test_output == ("from mycompany.model.size_value_array_import_func import \\\n"
+                           "    get_size_value_array_import_func_jobs\n")
Repository: timothycrosley/isort
Pull request #313 (2015-08-30 01:48:54)

Feature/fix issue 312/crash on simple file


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index bfaed295..6b0d22f9 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -334,7 +334,7 @@ class SortImports(object):
 
             comments_above = self.comments['above']['straight'].pop(module, None)
             if comments_above:
-                section_output.append(comments_above)
+                section_output.extend(comments_above)
             section_output.append(self._add_comments(self.comments['straight'].get(module), import_definition))
 
     def _add_from_imports(self, from_modules, section, section_output):
@@ -809,11 +809,13 @@ class SortImports(object):
                         if len(self.out_lines) > max(self.import_index, self._first_comment_index_end, 1) - 1:
                             last = self.out_lines and self.out_lines[-1].rstrip() or ""
                             while last.startswith("#") and not last.endswith('"""') and not last.endswith("'''"):
-                                self.comments['above']['from'].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:
-                                last = self.out_lines[-1].rstrip()
-                            else:
-                                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:
+                                    last = self.out_lines[-1].rstrip()
+                                else:
+                                    last = ""
                         self.imports[self.place_module(module)][import_type].add(module)
 
 


Test patch:
diff --git a/test_isort.py b/test_isort.py
index c1d194da..3506405c 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1499,3 +1499,11 @@ def test_top_of_line_comments():
                    'import logging\n')
     output = SortImports(file_contents=test_input).output
     assert output.startswith('# -*- coding: utf-8 -*-\n')
+
+
+def test_basic_comment():
+    """Test to ensure a basic comment wont crash isort"""
+    test_input = ('import logging\n'
+                  '# Foo\n'
+                  'import os\n')
+    assert SortImports(file_contents=test_input).output == test_input
Repository: timothycrosley/isort
Pull request #321 (2015-09-01 03:38:20)

Feature/fix issue 316


Patch:
diff --git a/isort/isort.py b/isort/isort.py
index 6b0d22f9..bec5c9c3 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -795,6 +795,8 @@ class SortImports(object):
                                 last = self.out_lines[-1].rstrip()
                             else:
                                 last = ""
+                        if self.index - 1 == self.import_index:
+                            self.import_index -= len(self.comments['above']['from'].get(import_from, []))
 
                     if root.get(import_from, False):
                         root[import_from].update(imports)
@@ -816,6 +818,8 @@ class SortImports(object):
                                     last = self.out_lines[-1].rstrip()
                                 else:
                                     last = ""
+                            if self.index - 1 == self.import_index:
+                                self.import_index -= len(self.comments['above']['straight'].get(module, []))
                         self.imports[self.place_module(module)][import_type].add(module)
 
 


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 3506405c..04a14cca 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1507,3 +1507,12 @@ def test_basic_comment():
                   '# Foo\n'
                   'import os\n')
     assert SortImports(file_contents=test_input).output == test_input
+
+
+def test_shouldnt_add_lines():
+    """Ensure that isort doesn't add a blank line when a top of import comment is present, issue #316"""
+    test_input = ('"""Text"""\n'
+                  '# This is a comment\n'
+                 'import pkg_resources\n')
+    assert SortImports(file_contents=test_input).output == test_input
+