Skip to content

Commit

Permalink
Improve b261af9 (Yelp#568)
Browse files Browse the repository at this point in the history
- move try-except up the stack, so we actually have a line number and
  not only the column
- also catch IndexError (eg. if the file has fewer lines than
  secret.line_number)
  • Loading branch information
clonejo committed Nov 6, 2022
1 parent 001e163 commit 6459b4d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
6 changes: 5 additions & 1 deletion detect_secrets/audit/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ..types import SecretContext
from ..util.color import AnsiColor
from ..util.color import colorize
from detect_secrets.exceptions import SecretNotFoundOnSpecifiedLineError


def print_message(message: str) -> None:
Expand All @@ -34,7 +35,10 @@ def print_context(context: SecretContext) -> None:

context.snippet.add_line_numbers()
if context.secret.secret_value:
context.snippet.highlight_line(context.secret.secret_value)
try:
context.snippet.highlight_line(context.secret.secret_value)
except (ValueError, IndexError):
raise SecretNotFoundOnSpecifiedLineError(context.secret.line_number)
else:
context.snippet.target_line = colorize(context.snippet.target_line, AnsiColor.BOLD)
print_message(str(context.snippet))
Expand Down
22 changes: 9 additions & 13 deletions detect_secrets/util/code_snippet.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from .color import AnsiColor
from .color import colorize
from detect_secrets.exceptions import SecretNotFoundOnSpecifiedLineError


def get_code_snippet(
Expand Down Expand Up @@ -72,19 +71,16 @@ def highlight_line(self, payload: str) -> 'CodeSnippet':
"""
:param payload: string to highlight, on chosen line
"""
try:
index_of_payload = self.target_line.lower().index(payload.lower())
end_of_payload = index_of_payload + len(payload)

self.target_line = u'{}{}{}'.format(
self.target_line[:index_of_payload],
self.apply_highlight(self.target_line[index_of_payload:end_of_payload]),
self.target_line[end_of_payload:],
)
index_of_payload = self.target_line.lower().index(payload.lower())
end_of_payload = index_of_payload + len(payload)

self.target_line = "{}{}{}".format(
self.target_line[:index_of_payload],
self.apply_highlight(self.target_line[index_of_payload:end_of_payload]),
self.target_line[end_of_payload:],
)

return self
except ValueError:
raise SecretNotFoundOnSpecifiedLineError(self.target_index)
return self

def get_line_number(self, line_number: int) -> str:
"""Broken out, for custom colorization."""
Expand Down

0 comments on commit 6459b4d

Please sign in to comment.