blob: bd0fc0981c8c6d7aee1df962b4a30c08e27a7ecd [file] [log] [blame]
Guido van Rossumbfc39441997-03-25 21:58:08 +00001"""Mailcap file handling. See RFC 1524."""
Guido van Rossum8988fb21995-09-30 16:52:24 +00002
3import os
R David Murray347dc952016-09-09 20:04:23 -04004import warnings
Guido van Rossum8988fb21995-09-30 16:52:24 +00005
Skip Montanaro17ab1232001-01-24 06:27:27 +00006__all__ = ["getcaps","findmatch"]
Guido van Rossum8988fb21995-09-30 16:52:24 +00007
R David Murray347dc952016-09-09 20:04:23 -04008
9def lineno_sort_key(entry):
10 # Sort in ascending order, with unspecified entries at the end
11 if 'lineno' in entry:
12 return 0, entry['lineno']
13 else:
14 return 1, 0
15
16
Guido van Rossum8988fb21995-09-30 16:52:24 +000017# Part 1: top-level interface.
18
19def getcaps():
Guido van Rossumbfc39441997-03-25 21:58:08 +000020 """Return a dictionary containing the mailcap database.
Tim Peters07e99cb2001-01-14 23:47:14 +000021
Guido van Rossum54f22ed2000-02-04 15:10:34 +000022 The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
23 to a list of dictionaries corresponding to mailcap entries. The list
24 collects all the entries for that MIME type from all available mailcap
25 files. Each dictionary contains key-value pairs for that MIME type,
26 where the viewing command is stored with the key "view".
Guido van Rossumbfc39441997-03-25 21:58:08 +000027
28 """
Guido van Rossum8988fb21995-09-30 16:52:24 +000029 caps = {}
R David Murray347dc952016-09-09 20:04:23 -040030 lineno = 0
Guido van Rossum8988fb21995-09-30 16:52:24 +000031 for mailcap in listmailcapfiles():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000032 try:
33 fp = open(mailcap, 'r')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +020034 except OSError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 continue
Serhiy Storchaka91b0bc22014-01-25 19:43:02 +020036 with fp:
R David Murray347dc952016-09-09 20:04:23 -040037 morecaps, lineno = _readmailcapfile(fp, lineno)
Guido van Rossumcc2b0162007-02-11 06:12:03 +000038 for key, value in morecaps.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +000039 if not key in caps:
Raymond Hettingere0d49722002-06-02 18:55:56 +000040 caps[key] = value
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000041 else:
Raymond Hettingere0d49722002-06-02 18:55:56 +000042 caps[key] = caps[key] + value
Guido van Rossum8988fb21995-09-30 16:52:24 +000043 return caps
44
45def listmailcapfiles():
Guido van Rossumbfc39441997-03-25 21:58:08 +000046 """Return a list of all mailcap files found on the system."""
Nick Coghlan20937302011-08-28 00:17:31 +100047 # This is mostly a Unix thing, but we use the OS path separator anyway
Raymond Hettinger54f02222002-06-01 14:18:47 +000048 if 'MAILCAPS' in os.environ:
Nick Coghlan20937302011-08-28 00:17:31 +100049 pathstr = os.environ['MAILCAPS']
50 mailcaps = pathstr.split(os.pathsep)
Guido van Rossum8988fb21995-09-30 16:52:24 +000051 else:
Raymond Hettinger54f02222002-06-01 14:18:47 +000052 if 'HOME' in os.environ:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000053 home = os.environ['HOME']
54 else:
55 # Don't bother with getpwuid()
56 home = '.' # Last resort
57 mailcaps = [home + '/.mailcap', '/etc/mailcap',
58 '/usr/etc/mailcap', '/usr/local/etc/mailcap']
Guido van Rossum8988fb21995-09-30 16:52:24 +000059 return mailcaps
60
61
62# Part 2: the parser.
Guido van Rossum8988fb21995-09-30 16:52:24 +000063def readmailcapfile(fp):
R David Murray347dc952016-09-09 20:04:23 -040064 """Read a mailcap file and return a dictionary keyed by MIME type."""
65 warnings.warn('readmailcapfile is deprecated, use getcaps instead',
66 DeprecationWarning, 2)
67 caps, _ = _readmailcapfile(fp, None)
68 return caps
69
70
71def _readmailcapfile(fp, lineno):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000072 """Read a mailcap file and return a dictionary keyed by MIME type.
73
74 Each MIME type is mapped to an entry consisting of a list of
75 dictionaries; the list will contain more than one such dictionary
76 if a given MIME type appears more than once in the mailcap file.
77 Each dictionary contains key-value pairs for that MIME type, where
78 the viewing command is stored with the key "view".
79 """
Guido van Rossum8988fb21995-09-30 16:52:24 +000080 caps = {}
81 while 1:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 line = fp.readline()
83 if not line: break
84 # Ignore comments and blank lines
Eric S. Raymond0c03cc22001-02-09 10:23:55 +000085 if line[0] == '#' or line.strip() == '':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 continue
87 nextline = line
88 # Join continuation lines
89 while nextline[-2:] == '\\\n':
90 nextline = fp.readline()
91 if not nextline: nextline = '\n'
92 line = line[:-2] + nextline
93 # Parse the line
94 key, fields = parseline(line)
95 if not (key and fields):
96 continue
R David Murray347dc952016-09-09 20:04:23 -040097 if lineno is not None:
98 fields['lineno'] = lineno
99 lineno += 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 # Normalize the key
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000101 types = key.split('/')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000102 for j in range(len(types)):
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000103 types[j] = types[j].strip()
104 key = '/'.join(types).lower()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000105 # Update the database
Raymond Hettinger54f02222002-06-01 14:18:47 +0000106 if key in caps:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 caps[key].append(fields)
108 else:
109 caps[key] = [fields]
R David Murray347dc952016-09-09 20:04:23 -0400110 return caps, lineno
Guido van Rossum8988fb21995-09-30 16:52:24 +0000111
112def parseline(line):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000113 """Parse one entry in a mailcap file and return a dictionary.
114
115 The viewing command is stored as the value with the key "view",
116 and the rest of the fields produce key-value pairs in the dict.
117 """
Guido van Rossum8988fb21995-09-30 16:52:24 +0000118 fields = []
119 i, n = 0, len(line)
120 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 field, i = parsefield(line, i, n)
122 fields.append(field)
123 i = i+1 # Skip semicolon
Guido van Rossum8988fb21995-09-30 16:52:24 +0000124 if len(fields) < 2:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 return None, None
Guido van Rossum8988fb21995-09-30 16:52:24 +0000126 key, view, rest = fields[0], fields[1], fields[2:]
127 fields = {'view': view}
128 for field in rest:
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000129 i = field.find('=')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 if i < 0:
131 fkey = field
132 fvalue = ""
133 else:
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000134 fkey = field[:i].strip()
135 fvalue = field[i+1:].strip()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000136 if fkey in fields:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000137 # Ignore it
138 pass
139 else:
140 fields[fkey] = fvalue
Guido van Rossum8988fb21995-09-30 16:52:24 +0000141 return key, fields
142
143def parsefield(line, i, n):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000144 """Separate one key-value pair in a mailcap entry."""
Guido van Rossum8988fb21995-09-30 16:52:24 +0000145 start = i
146 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000147 c = line[i]
148 if c == ';':
149 break
150 elif c == '\\':
151 i = i+2
152 else:
153 i = i+1
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000154 return line[start:i].strip(), i
Guido van Rossum8988fb21995-09-30 16:52:24 +0000155
156
157# Part 3: using the database.
158
Guido van Rossumbfc39441997-03-25 21:58:08 +0000159def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
160 """Find a match for a mailcap entry.
Tim Peters07e99cb2001-01-14 23:47:14 +0000161
Guido van Rossumbfc39441997-03-25 21:58:08 +0000162 Return a tuple containing the command line, and the mailcap entry
163 used; (None, None) if no match is found. This may invoke the
164 'test' command of several matching entries before deciding which
165 entry to use.
166
167 """
168 entries = lookup(caps, MIMEtype, key)
Tim Peters07e99cb2001-01-14 23:47:14 +0000169 # XXX This code should somehow check for the needsterminal flag.
Guido van Rossum8988fb21995-09-30 16:52:24 +0000170 for e in entries:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000171 if 'test' in e:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 test = subst(e['test'], filename, plist)
173 if test and os.system(test) != 0:
174 continue
175 command = subst(e[key], MIMEtype, filename, plist)
176 return command, e
Guido van Rossum8988fb21995-09-30 16:52:24 +0000177 return None, None
178
Guido van Rossumbfc39441997-03-25 21:58:08 +0000179def lookup(caps, MIMEtype, key=None):
Guido van Rossum8988fb21995-09-30 16:52:24 +0000180 entries = []
Raymond Hettinger54f02222002-06-01 14:18:47 +0000181 if MIMEtype in caps:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 entries = entries + caps[MIMEtype]
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000183 MIMEtypes = MIMEtype.split('/')
Guido van Rossumbfc39441997-03-25 21:58:08 +0000184 MIMEtype = MIMEtypes[0] + '/*'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000185 if MIMEtype in caps:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 entries = entries + caps[MIMEtype]
Guido van Rossum8988fb21995-09-30 16:52:24 +0000187 if key is not None:
Antoine Pitrou7062db82010-04-22 13:30:10 +0000188 entries = [e for e in entries if key in e]
R David Murray347dc952016-09-09 20:04:23 -0400189 entries = sorted(entries, key=lineno_sort_key)
Guido van Rossum8988fb21995-09-30 16:52:24 +0000190 return entries
191
Guido van Rossumbfc39441997-03-25 21:58:08 +0000192def subst(field, MIMEtype, filename, plist=[]):
Guido van Rossum8988fb21995-09-30 16:52:24 +0000193 # XXX Actually, this is Unix-specific
194 res = ''
195 i, n = 0, len(field)
196 while i < n:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 c = field[i]; i = i+1
Fred Drake8152d322000-12-12 23:20:45 +0000198 if c != '%':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 if c == '\\':
200 c = field[i:i+1]; i = i+1
201 res = res + c
202 else:
203 c = field[i]; i = i+1
204 if c == '%':
205 res = res + c
206 elif c == 's':
207 res = res + filename
208 elif c == 't':
209 res = res + MIMEtype
210 elif c == '{':
211 start = i
Fred Drake8152d322000-12-12 23:20:45 +0000212 while i < n and field[i] != '}':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 i = i+1
214 name = field[start:i]
215 i = i+1
216 res = res + findparam(name, plist)
217 # XXX To do:
218 # %n == number of parts if type is multipart/*
219 # %F == list of alternating type and filename for parts
220 else:
221 res = res + '%' + c
Guido van Rossum8988fb21995-09-30 16:52:24 +0000222 return res
223
224def findparam(name, plist):
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000225 name = name.lower() + '='
Guido van Rossum8988fb21995-09-30 16:52:24 +0000226 n = len(name)
227 for p in plist:
Eric S. Raymond0c03cc22001-02-09 10:23:55 +0000228 if p[:n].lower() == name:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 return p[n:]
Guido van Rossum8988fb21995-09-30 16:52:24 +0000230 return ''
231
232
233# Part 4: test program.
234
235def test():
236 import sys
237 caps = getcaps()
238 if not sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 show(caps)
240 return
Guido van Rossum8988fb21995-09-30 16:52:24 +0000241 for i in range(1, len(sys.argv), 2):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 args = sys.argv[i:i+2]
243 if len(args) < 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000244 print("usage: mailcap [MIMEtype file] ...")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 return
246 MIMEtype = args[0]
247 file = args[1]
248 command, e = findmatch(caps, MIMEtype, 'view', file)
249 if not command:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print("No viewer found for", type)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print("Executing:", command)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 sts = os.system(command)
254 if sts:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000255 print("Exit status:", sts)
Guido van Rossum8988fb21995-09-30 16:52:24 +0000256
257def show(caps):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000258 print("Mailcap files:")
259 for fn in listmailcapfiles(): print("\t" + fn)
260 print()
Guido van Rossum8988fb21995-09-30 16:52:24 +0000261 if not caps: caps = getcaps()
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000262 print("Mailcap entries:")
263 print()
Antoine Pitrou945c17f2010-04-22 13:19:31 +0000264 ckeys = sorted(caps)
Guido van Rossum8988fb21995-09-30 16:52:24 +0000265 for type in ckeys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000266 print(type)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 entries = caps[type]
268 for e in entries:
Antoine Pitrou945c17f2010-04-22 13:19:31 +0000269 keys = sorted(e)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000270 for k in keys:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000271 print(" %-15s" % k, e[k])
272 print()
Guido van Rossum8988fb21995-09-30 16:52:24 +0000273
274if __name__ == '__main__':
275 test()