-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_safari_bookmarks
executable file
·58 lines (43 loc) · 1.41 KB
/
import_safari_bookmarks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python3
"""
Import bookmarks to Safari from a Netscape Bookmark file.
Bookmark folders are ignored.
Usage: import_safari_bookmarks <path/to/bookmarks.html>
"""
import plistlib
import re
import sys
import uuid
from pathlib import Path
def main() -> None:
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
input_path = Path(sys.argv[1])
text = input_path.read_text()
bookmarks: list[object] = []
for match in re.finditer(r'<DT><A HREF="(.*?)".*>(.*)</A>', text):
bookmarks.append(
{
"ReadingListNonSync": {"neverFetchMetadata": 0},
"URIDictionary": {"title": match.group(2)},
"URLString": match.group(1),
"WebBookmarkType": "WebBookmarkTypeLeaf",
"WebBookmarkUUID": random_uuid(),
}
)
if len(bookmarks) == 0:
print(f"no bookmarks found in {input_path}")
sys.exit(0)
output_path = Path("~/Library/Safari/Bookmarks.plist").expanduser()
with open(output_path, mode="r+b") as f:
data = plistlib.load(f, fmt=plistlib.FMT_BINARY)
f.seek(0)
data["WebBookmarkUUID"] = random_uuid()
data["Children"][3:] = bookmarks
plistlib.dump(data, f, fmt=plistlib.FMT_BINARY, sort_keys=False)
f.truncate()
def random_uuid() -> str:
return str(uuid.uuid4()).upper()
if __name__ == "__main__":
main()