1# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- 2# vim: set filetype=python: 3# This Source Code Form is subject to the terms of the Mozilla Public 4# License, v. 2.0. If a copy of the MPL was not distributed with this 5# file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 7 8@template 9def keyfile(desc, default=None, help=None, callback=lambda x: x): 10 help = help or ( 11 "Use the secret key contained in the given keyfile " "for %s requests" % desc 12 ) 13 name = desc.lower().replace(" ", "-") 14 no_key = callback("no-%s-key" % name) 15 16 option("--with-%s-keyfile" % name, nargs=1, default=default, help=help) 17 18 @depends("--with-%s-keyfile" % name) 19 @checking("for the %s key" % desc, lambda x: x and x is not no_key) 20 @imports(_from="__builtin__", _import="open") 21 @imports(_from="__builtin__", _import="IOError") 22 @imports(_from="os", _import="environ") 23 def keyfile(value): 24 if value: 25 try: 26 with open(value[0]) as fh: 27 result = fh.read().strip() 28 if result: 29 return callback(result) 30 raise FatalCheckError("'%s' is empty." % value[0]) 31 except IOError as e: 32 raise FatalCheckError("'%s': %s." % (value[0], e.strerror)) 33 return environ.get("MOZ_%s_KEY" % desc.upper().replace(" ", "_")) or no_key 34 35 return keyfile 36 37 38@template 39def simple_keyfile(desc, default=None): 40 value = keyfile(desc, default=default) 41 set_config("MOZ_%s_KEY" % desc.upper().replace(" ", "_"), value) 42 43 44@template 45def id_and_secret_keyfile(desc, default=None): 46 def id_and_secret(value): 47 if value.startswith("no-") and value.endswith("-key"): 48 id = value[:-3] + "clientid" 49 secret = value 50 elif " " in value: 51 id, secret = value.split(" ", 1) 52 else: 53 raise FatalCheckError("%s key file has an invalid format." % desc) 54 return namespace( 55 id=id, 56 secret=secret, 57 ) 58 59 content = keyfile( 60 desc, 61 help="Use the client id and secret key contained " 62 "in the given keyfile for %s requests" % desc, 63 default=default, 64 callback=id_and_secret, 65 ) 66 67 name = desc.upper().replace(" ", "_") 68 set_config("MOZ_%s_CLIENTID" % name, content.id) 69 set_config("MOZ_%s_KEY" % name, content.secret) 70