Skip to content

Commit fd3fbe8

Browse files
authored
Fix --insert-license-after-regex to work beyond first line (#103)
There was a logic bug where `index` wasn't incremenetd, so we would search through the file for the regex, but index was still 0 so the index always got put after line 0.
1 parent 24c29be commit fd3fbe8

File tree

4 files changed

+20
-6
lines changed

4 files changed

+20
-6
lines changed

pre_commit_hooks/insert_license.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ def license_not_found( # pylint: disable=too-many-arguments
328328
"""
329329
if not remove_header:
330330
index = 0
331-
for line in src_file_content:
331+
for index, line in enumerate(src_file_content):
332332
stripped_line = line.strip()
333333
# Special treatment for user provided regex,
334334
# or shebang, file encoding directive,
@@ -339,13 +339,14 @@ def license_not_found( # pylint: disable=too-many-arguments
339339
index += 1 # Skip matched line
340340
break # And insert after that line.
341341
elif (
342-
stripped_line.startswith("#!")
343-
or stripped_line.startswith("# -*- coding")
344-
or stripped_line == ""
342+
not stripped_line.startswith("#!")
343+
and not stripped_line.startswith("# -*- coding")
344+
and not stripped_line == ""
345345
):
346-
index += 1
347-
else:
348346
break
347+
else:
348+
# We got all the way to the end without hitting `break`, reset it to line 0
349+
index = 0
349350
src_file_content = (
350351
src_file_content[:index]
351352
+ license_info.prefixed_license

tests/insert_license_test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,15 @@ def _convert_line_ending(file_path, new_line_endings):
190190
True,
191191
["--insert-license-after-regex", "^<\\?php$"],
192192
),
193+
(
194+
"module_without_license.py",
195+
"#",
196+
"module_with_license.py",
197+
"",
198+
True,
199+
# Test that when the regex is not found, the license is put at the first line
200+
["--insert-license-after-regex", "^<\\?php$"],
201+
),
193202
(
194203
"module_without_license.py",
195204
"#",

tests/resources/module_with_license.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
<!-- Hi -->
2+
<html>
13
<?php
24
/*
35
* Copyright (C) 2017 Teela O'Malley
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
1+
<!-- Hi -->
2+
<html>
13
<?php
24
print "Hello";

0 commit comments

Comments
 (0)