Last active
September 16, 2024 11:50
-
-
Save masterflitzer/cf0c369d79332407ad429867a9d80c65 to your computer and use it in GitHub Desktop.
Simple script to filter or filter out events of an ics file based on their name (summary) using regex
This file contains 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
#!/usr/bin/env python3 | |
from ics import Calendar | |
import argparse | |
import re | |
import sys | |
def main(): | |
arg_parser = argparse.ArgumentParser() | |
arg_parser.add_argument("-i", "--input", help="Input file in ics format") | |
arg_parser.add_argument( | |
"-f", "--filter", help="RegEx filter events by summary/name" | |
) | |
arg_parser.add_argument( | |
"-fo", "--filterout", help="RegEx filter out events by summary/name" | |
) | |
arg_parser.add_argument("-o", "--output", help="Output file in ics format") | |
args = arg_parser.parse_args() | |
input_file = args.input | |
output_file = args.output | |
if not input_file or not output_file: | |
print("Please provide a path to an input and output file!") | |
sys.exit(1) | |
re_filter = None if args.filter is None else re.compile(args.filter, re.I) | |
re_filterout = None if args.filterout is None else re.compile(args.filterout, re.I) | |
if not (bool(re_filter) ^ bool(re_filterout)): | |
print("You can either provide filter or filterout, not both or neither!") | |
sys.exit(1) | |
cal = None | |
with open(input_file, "r") as f: | |
cal = Calendar(f.read()) | |
if re_filter: | |
cal.events = { | |
event for event in cal.events if bool(re.search(re_filter, event.name)) | |
} | |
if re_filterout: | |
cal.events = { | |
event | |
for event in cal.events | |
if not bool(re.search(re_filterout, event.name)) | |
} | |
with open(output_file, "w", newline="\n") as f: | |
f.writelines(cal.serialize_iter()) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment