1
0
Fork 0
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""
This is an even simpler script to combine multiple mimeapps.list files into
one.
This is not too trivial, since an addition can be reverted by a deletion in a
later file and vice versa, and all values should probably be deduplicated.
The input files are processed left-to-right. This means that the default is
taken from the leftmost (first supplied) file the respective MIME type is
specified (other files serve as fallbacks), but an association added in one
file can be reverted in a later file (and possibly re-added in even later file)
"""
from pathlib import Path
from dataclasses import dataclass
import sys
import re
DEBUG = 1
def _dprint(lvl):
def f(*a, **kw):
if DEBUG >= lvl:
print(*a, **kw | {'file': sys.stderr})
return f
dprint = _dprint(1)
ddprint = _dprint(2)
def combine_dicts_with_lists(d1, d2):
result = {}
result |= {k: (d1|d2)[k] for k in d1.keys() ^ d2.keys()}
result |= {k: d1[k] + d2[k] for k in d1.keys() & d2.keys()}
return result
if '--help' in sys.argv or len(sys.argv) <= 1:
print(f'Usage: {sys.argv[0]} file ...\n\nThis script combines multiple mimeapps.list files into one.', file=sys.stderr)
sys.exit()
ADDITIONS = {}
DELETIONS = {}
DEFAULTS = {}
for fn in sys.argv[1:]:
section = None
with open(fn) as f:
for line in f:
line = line.strip()
if line.startswith('['):
section = re.match(r'\[[^]]+\]', line).string
dprint(f'DEBUG: Found section \'{section}\'')
continue
mimetype, apps = line.split('=', 2)
apps = [x for x in apps.split(';') if x != '']
if section == '[Added Associations]':
if mimetype not in ADDITIONS:
ADDITIONS[mimetype] = []
for app in apps:
if app not in ADDITIONS[mimetype]:
ADDITIONS[mimetype].append(app)
if mimetype in DELETIONS and app in DELETIONS[mimetype]:
DELETIONS[mimetype].remove(app)
if section == '[Removed Associations]':
if mimetype not in DELETIONS:
DELETIONS[mimetype] = []
for app in apps:
if app not in DELETIONS[mimetype]:
DELETIONS[mimetype].append(app)
if mimetype in ADDITIONS and app in ADDITIONS[mimetype]:
ADDITIONS[mimetype].remove(app)
if section == '[Default Applications]':
if mimetype not in DEFAULTS:
DEFAULTS[mimetype] = []
for app in apps:
if app not in DEFAULTS[mimetype]:
dprint(f'adding {app} to {mimetype}')
DEFAULTS[mimetype].append(app)
if ADDITIONS:
print('[Added Associations]')
for mt, apps in ADDITIONS.items():
print(f"{mt}={';'.join(apps)};")
print()
if DELETIONS:
print('[Removed Associations]')
for mt, apps in DELETIONS.items():
print(f"{mt}={';'.join(apps)};")
print()
if DEFAULTS:
print('[Default Applications]')
for mt, apps in DEFAULTS.items():
print(f"{mt}={';'.join(apps)};")
print()