Skip to content

Commit

Permalink
Fix issue #67: Correctly skip imports withing strings
Browse files Browse the repository at this point in the history
  • Loading branch information
timothycrosley committed Nov 4, 2013
1 parent 0203832 commit b304f82
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
19 changes: 18 additions & 1 deletion isort/isort.py
Expand Up @@ -315,10 +315,27 @@ def _parse(self):
"""
Parses a python file taking out and categorizing imports
"""
in_long_quote = False
while not self._at_end():
line = self._get_line()
if ('"""' in line or "'''" in line) and not line.startswith("#"):
in_short_quote = False
for index, character in enumerate(line):
if in_short_quote:
if in_short_quote == character:
in_short_quote = False
elif character in ("'", '"'):
long_quote = line[index:index + 3]
if long_quote in ('"""', "'''"):
if in_long_quote == long_quote:
in_long_quote = False
else:
in_long_quote = long_quote
elif not in_long_quote:
in_short_quote = character

import_type = self._import_type(line)
if not import_type:
if not import_type or in_long_quote:
self.out_lines.append(line)
continue

Expand Down
1 change: 1 addition & 0 deletions isort/settings.py
Expand Up @@ -60,6 +60,7 @@
'known_third_party': ['google.appengine.api'],
'known_first_party': [],
'multi_line_output': WrapModes.GRID,
'forced_separate': [],
'indent': ' ' * 4,
'length_sort': False,
'add_imports': [],
Expand Down
34 changes: 34 additions & 0 deletions test_isort.py
Expand Up @@ -381,6 +381,40 @@ def test_quotes_in_file():
'"""\n')
assert SortImports(file_contents=test_input).output == test_input

test_input = ('import os\n'
'\n'
"'\"\"\"'\n"
'import foo\n')
assert SortImports(file_contents=test_input).output == ('import os\n'
'\n'
'import foo\n'
'\n'
"'\"\"\"'\n")

test_input = ('import os\n'
'\n'
'"""Let us"""\n'
'import foo\n'
'"""okay?"""\n')
assert SortImports(file_contents=test_input).output == ('import os\n'
'\n'
'import foo\n'
'\n'
'"""Let us"""\n'
'"""okay?"""\n')

test_input = ('import os\n'
'\n'
'#"""\n'
'import foo\n'
'#"""')
assert SortImports(file_contents=test_input).output == ('import os\n'
'\n'
'import foo\n'
'\n'
'#"""\n'
'#"""\n')


def test_check_newline_in_imports(capsys):
"""
Expand Down

0 comments on commit b304f82

Please sign in to comment.