Project

General

Profile

Feature #2942 » create-mime.assign.py

Alternative implementation of create-mime.assign.pl in python - geusebi, 2019-03-14 02:36

 
1
#!/usr/bin/env python
2

    
3
from sys import exit
4
import re
5

    
6
# match a simplified form of rule with
7
# at least one extension
8
rule = re.compile("""
9
    ([a-z0-9\/.+-]+)
10
    \s+
11
    ([a-z0-9.+-][a-z0-9. +-]*)
12
""", re.IGNORECASE | re.VERBOSE)
13

    
14
try:
15
    mime_file = open("/etc/mime.types", "r")
16

    
17
    # collapse lines ending with a slash
18
    text = re.sub(r"\\(\n|(\r\n?))", "", mime_file.read())
19
except (OSError, IOError):
20
    exit()
21

    
22
print("mimetype.assign = (")
23

    
24
types = set()
25
for line in map(str.strip, text.splitlines()):
26
    # rule matching will prevent comments or
27
    # empty lines to pass
28

    
29
    match = rule.match(line)
30
    if not match:
31
        continue
32
    
33
    mime, exts = match.groups()
34

    
35
    for ext in exts.split():
36
        if not ext in types:
37
            types.add(ext)
38
            print('".%s" => "%s",' % (ext, mime.lower()))
39

    
40
print(")")
(2-2/2)