Last active
July 24, 2023 13:38
-
-
Save Kelfitas/845728be8451d016af79b06257ce0872 to your computer and use it in GitHub Desktop.
Deletes events from an ics file based on regex filter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import sys | |
def print_usage(): | |
print("Usage: python3 ./ics-filter.py [file] [regex_filter]") | |
n = len(sys.argv) | |
if n < 2: | |
print("No ics file provided") | |
print_usage() | |
exit(1) | |
if n < 3: | |
print("No filter provided") | |
print_usage() | |
exit(1) | |
filename = sys.argv[1] | |
event_filter = re.compile(sys.argv[2]) | |
def should_add_event(event_data: str, filter: re.Pattern) -> bool: | |
return filter.search(event_data) is None | |
new_file_contents = "" | |
with open(filename, encoding="utf-8") as f: | |
read_data = f.read() | |
current_event_data = [] | |
is_reading_event_data = False | |
new_file_contents_list = [] | |
for line in read_data.split("\n"): | |
if line == "BEGIN:VEVENT": | |
is_reading_event_data = True | |
if is_reading_event_data: | |
current_event_data.append(line) | |
else: | |
new_file_contents_list.append(line) | |
if line == "END:VEVENT": | |
joined_current_event_data = "\n".join(current_event_data) | |
if should_add_event(joined_current_event_data, event_filter): | |
new_file_contents_list.append(joined_current_event_data) | |
current_event_data = [] | |
is_reading_event_data = False | |
new_file_contents = "\n".join(new_file_contents_list) | |
with open(filename + ".bkp", mode="w", encoding="utf-8") as f_bkp: | |
f_bkp.write(read_data) | |
with open(filename, mode="w", encoding="utf-8") as f: | |
f.write(new_file_contents) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment