From bf591c2dd0dee6d84f2d5223ecbe84bc9f89715a Mon Sep 17 00:00:00 2001 From: Isis Lovecruft Date: Mon, 27 May 2013 08:12:54 +0000 Subject: [PATCH] Add a utility for creating a 'user@hostname' string. --- src/_util.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/_util.py b/src/_util.py index bd1a027..1ebc8f3 100644 --- a/src/_util.py +++ b/src/_util.py @@ -22,6 +22,7 @@ Extra utilities for python-gnupg. ''' from datetime import datetime +from socket import gethostname import codecs import encodings @@ -173,6 +174,39 @@ def _create_if_necessary(directory): log.debug("Created directory.") return True +def create_uid_email(username=None, hostname=None): + """Create an email address suitable for a UID on a GnuPG key. + + :param str username: The username portion of an email address. If None, + defaults to the username of the running Python + process. + + :param str hostname: The FQDN portion of an email address. If None, the + hostname is obtained from gethostname(2). + + :rtype: str + :returns: A string formatted as @. + """ + if hostname: + hostname = hostname.replace(' ', '_') + if not username: + try: username = os.environ['LOGNAME'] + except KeyError: username = os.environ['USERNAME'] + + if not hostname: hostname = gethostname() + + uid = "%s@%s" % (username.replace(' ', '_'), hostname) + else: + username = username.replace(' ', '_') + if (not hostname) and (username.find('@') == 0): + uid = "%s@%s" % (username, gethostname()) + elif hostname: + uid = "%s@%s" % (username, hostname) + else: + uid = username + + return uid + def _find_binary(binary=None): """Find the absolute path to the GnuPG binary.