2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Utility to package and upload the USB gadget framework.
17 def MakeZip(directory
=None, files
=None):
18 """Construct a zip file.
21 directory: Include Python source files from this directory
22 files: Include these files
25 A tuple of the buffer containing the zip file and its MD5 hash.
27 buf
= StringIO
.StringIO()
28 archive
= zipfile
.PyZipFile(buf
, 'w')
29 if directory
is not None:
30 archive
.writepy(directory
)
33 archive
.write(f
, os
.path
.basename(f
))
35 content
= buf
.getvalue()
37 md5
= hashlib
.md5(content
).hexdigest()
41 def EncodeBody(filename
, buf
):
44 'Content-Disposition: form-data; name="file"; filename="{}"'
46 'Content-Type: application/octet-stream',
54 def UploadZip(content
, md5
, host
):
55 filename
= 'usb_gadget-{}.zip'.format(md5
)
56 req
= urllib2
.Request(url
='http://{}/update'.format(host
),
57 data
=EncodeBody(filename
, content
))
58 req
.add_header('Content-Type', 'multipart/form-data; boundary=foo')
63 parser
= argparse
.ArgumentParser(
64 description
='Package (and upload) the USB gadget framework.')
66 '--dir', type=str, metavar
='DIR',
67 help='package all Python files from DIR')
69 '--zip-file', type=str, metavar
='FILE',
70 help='save package as FILE')
72 '--hash-file', type=str, metavar
='FILE',
73 help='save package hash as FILE')
75 '--upload', type=str, metavar
='HOST[:PORT]',
76 help='upload package to target system')
78 'files', metavar
='FILE', type=str, nargs
='*',
81 args
= parser
.parse_args()
83 content
, md5
= MakeZip(directory
=args
.dir, files
=args
.files
)
85 with
open(args
.zip_file
, 'wb') as zip_file
:
86 zip_file
.write(content
)
88 with
open(args
.hash_file
, 'wb') as hash_file
:
91 UploadZip(content
, md5
, args
.upload
)
94 if __name__
== '__main__':