Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion bin/idstack-learnings-promote
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@ global_file = '$GLOBAL_LEARNINGS'

# Find matching learning
match = None
for line in open(local_file):
for line in reversed(list(open(local_file))):
if key not in line:
continue
Comment on lines +33 to +35

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There are two issues with the current implementation:

  1. Resource Leak: open(local_file) is called without being closed or wrapped in a with statement, leaving the file descriptor open.
  2. Correctness Bug with Escaped Keys: If key contains characters that are escaped in JSON (such as double quotes " or backslashes \), the literal key string will not be found in the raw JSON line, causing the match to be incorrectly skipped.

We can resolve both issues by:

  • Reading the file within a with block to ensure proper closure.
  • Pre-computing the JSON-escaped version of the key using json.dumps(key)[1:-1] before the loop.
escaped_key = json.dumps(key)[1:-1]
with open(local_file) as f:
    lines = f.readlines()
for line in reversed(lines):
    if escaped_key not in line:
        continue

try:
d = json.loads(line)
if d.get('key') == key:
match = d
break
except:
pass

Expand Down