Skip to content

Instantly share code, notes, and snippets.

@mjpost
Created August 20, 2015 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjpost/9eee2505246d79b71fa1 to your computer and use it in GitHub Desktop.
Save mjpost/9eee2505246d79b71fa1 to your computer and use it in GitHub Desktop.
Rebuilds Apple Calendar *.ics files so they can be safely reimported
#!/usr/bin/env python
"""
Looks at all the *.ics files in the current directory, removes the X- keys,
and generates a new UUID. This is used for restoring an accidentally-deleted
calendar in Apple's Calendar program; it is a rewrite of the node.js version
that is linked to from here:
http://fokkezb.nl/2015/01/13/how-to-restore-a-deleted-icloud-calendar/
"""
import os
import sys
import uuid
import codecs
import argparse
# Standard UTF-8 Python header that fixes sucky python UTF-8 handling
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdin = codecs.getreader('utf-8')(sys.stdin)
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
sys.stdout.encoding = 'utf-8'
parser = argparse.ArgumentParser()
parser.add_argument('-output_dir', help='the output directory to write to', default='output')
args = parser.parse_args()
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
for file in os.listdir('.'):
if file.endswith('.ics'):
lines = []
outfile = None
for line in codecs.open(file, 'r', 'utf-8'):
if line.startswith('X-'):
continue
elif line.startswith('UID:'):
parts = line.split(':')
lines.append('UID:%s\r\n' % (str(uuid.uuid4()).upper()))
outfile = '%s/%s.ics' % (args.output_dir, str(uuid.uuid4()).upper())
else:
lines.append(line)
print file, '->', outfile
out = codecs.open(outfile, 'w', 'utf-8')
for line in lines:
out.write(line)
out.close()
@florianmastacan
Copy link

Lovely, you saved my day with this script as iCloud was not able to restore my deleted calendars...

@mjpost
Copy link
Author

mjpost commented Oct 3, 2019

I only vaguely remember writing this and can't remember what problem I was solving, but I'm glad it was of some help to you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment