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
31 changes: 17 additions & 14 deletions bin/idstack-learnings-delete
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,33 @@ if ! command -v python3 &>/dev/null; then
fi

python3 -c "
import json, sys
import json, sys, os

key = sys.argv[1]
learnings_file = '$LEARNINGS'

lines = open(learnings_file).readlines()
# Find the last line with this key and remove it
# Find the last line with this key
found_idx = -1
for i, line in enumerate(lines):
try:
d = json.loads(line)
if d.get('key') == key:
found_idx = i
except:
pass
with open(learnings_file, 'r') as f:
for i, line in enumerate(f):
try:
d = json.loads(line)
if d.get('key') == key:
found_idx = i
except:
pass
Comment on lines +29 to +34

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Avoid using a bare except: clause as it catches all exceptions, including SystemExit and KeyboardInterrupt. This can make the script difficult to terminate via Ctrl+C and may hide unexpected bugs. It is better to catch the specific exception expected from json.loads and use an explicit type check to ensure the line is a dictionary before accessing its keys.

        try:
            d = json.loads(line)
            if isinstance(d, dict) and d.get('key') == key:
                found_idx = i
        except json.JSONDecodeError:
            pass
References
  1. PEP 8 recommends avoiding bare except: clauses because they catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program and potentially disguising other problems. (link)


if found_idx == -1:
print(f'No learning found with key: {key}', file=sys.stderr)
sys.exit(1)

# Remove that line
lines.pop(found_idx)
with open(learnings_file, 'w') as f:
f.writelines(lines)
# Write to temp file skipping the line to remove
temp_file = learnings_file + '.tmp'
with open(learnings_file, 'r') as f_in, open(temp_file, 'w') as f_out:
for i, line in enumerate(f_in):
if i != found_idx:
f_out.write(line)

os.replace(temp_file, learnings_file)
print(f'Deleted learning: {key}')
" "$KEY"