#!/usr/bin/env python3
# Remove all hunks from a patch that don't add the id attribute to minimize the impact (removed
# comments etc.) of sigma-uuid script.
#
# Usually used as follows:
# 1. Add UUIDs to rules:
# tools/sigma-uuid -er rules
# 2. Generate and filter patch
# git diff | contrib/filter-uuid-patch > rule-uuid.diff
# 3. Reset to previous state
# git reset --hard
# 4. Apply filtered patch
# patch -p1 < rule-uuid.diff
#
# This tool requires an installed unidiff package.

from unidiff import PatchSet
from sys import argv, stdin

try:
    with open(argv[1], "r") as f:
        patch = PatchSet(f.readlines())
except IndexError:
    patch = PatchSet(stdin.readlines())

for patched_file in patch:
    for h in reversed(range(len(patched_file))):
        hunk = patched_file[h]
        if not any([ line.is_added and line.value.startswith("id: ") for line in hunk ]):
            del patched_file[h]

print(str(patch))
