-
Notifications
You must be signed in to change notification settings - Fork 31
/
write-mime-multipart
executable file
·105 lines (81 loc) · 2.84 KB
/
write-mime-multipart
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python
import os
import sys
import argparse
import mimetypes
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
starts_with_mappings = {
'#include': 'text/x-include-url',
'#!': 'text/x-shellscript',
'#cloud-config': 'text/cloud-config',
'#upstart-job': 'text/upstart-job',
'#part-handler': 'text/part-handler',
'#cloud-boothook': 'text/cloud-boothook',
'#kube-pod': 'text/x-kube-pod',
'#kube-service': 'text/x-kube-service',
'#kube-replica': 'text/x-kube-replica',
}
mimetypes.add_type('text/x-markdown', '.md')
mimetypes.add_type('text/x-kube-pod', '.pod')
mimetypes.add_type('text/x-kube-service', '.service')
mimetypes.add_type('text/x-kube-replica', '.replica')
def guess_mimetype(path):
global args
with open(path) as fd:
firstline = fd.readline()
for value, mimetype in starts_with_mappings.items():
if firstline.startswith(value):
return mimetype, None
mimetype = mimetypes.guess_type(path)
return mimetype if mimetype else args.default_mimetype
def parse_args():
p = argparse.ArgumentParser()
p.add_argument('--output', '-o')
p.add_argument('--merge', '-M')
p.add_argument('--default-mimetype', '-T',
default='application/octet-stream')
p.add_argument('part', nargs='+')
return p.parse_args()
def main():
global args
args = parse_args()
container = MIMEMultipart()
for part in args.part:
if ':' in part:
path, mimetype = part.split(':')
encoding = None
else:
path = part
mimetype, encoding = guess_mimetype(path)
if mimetype is None:
print >>sys.stderr, 'ERROR: unable to determine mime type ' \
'for file $part.'
sys.exit(1)
maintype, subtype = mimetype.split('/', 1)
with open(path) as fd:
content = fd.read()
if maintype == 'text':
data = MIMEText(content, _subtype=subtype)
elif maintype == 'image':
data = MIMEImage(content, _subtype=subtype)
elif maintype == 'audio':
data = MIMEAudio(content, _subtype=subtype)
else:
data = MIMEBase(maintype, subtype)
with open(path) as fd:
data.set_payload(fd.read())
encoders.encode_base64(data)
if args.merge:
data.add_header('X-Merge-Type',
args.merge)
container.attach(data)
with open(args.output, 'w') if args.output else sys.stdout as fd:
fd.write(container.as_string())
if __name__ == '__main__':
main()