]> scripts.mit.edu Git - wizard.git/blob - wizard/util.py
5c5a63186f1e388195f660af6f1deb57c9ceec98
[wizard.git] / wizard / util.py
1 import os.path
2 import os
3 import subprocess
4 import pwd
5 import sys
6
7 import wizard
8
9 class ChangeDirectory(object):
10     """Context for temporarily changing directory"""
11     def __init__(self, dir):
12         self.dir = dir
13         self.olddir = None
14     def __enter__(self):
15         self.olddir = os.getcwd()
16         os.chdir(self.dir)
17     def __exit__(self, *args):
18         os.chdir(self.olddir)
19
20 def get_exception_name(output):
21     """Reads the stderr output of another Python command and grabs the
22     fully qualified exception name"""
23     lines = output.split("\n")
24     for line in lines[1:]: # skip the "traceback" line
25         line = line.rstrip()
26         if line[0] == ' ': continue
27         if line[-1] == ":":
28             return line[:-1]
29         else:
30             return line
31
32 def get_dir_uid(dir):
33     """Finds the uid of the person who owns this directory."""
34     return os.stat(dir).st_uid
35
36 def get_dir_owner(dir = "."):
37     """Finds the name of the locker this directory is in."""
38     return pwd.getpwuid(get_dir_uid(dir)).pw_name
39
40 def get_revision():
41     """Returns the commit ID of the current Wizard install."""
42     wizard_git = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".git")
43     return subprocess.Popen(["git", "--git-dir=" + wizard_git, "rev-parse", "HEAD"], stdout=subprocess.PIPE).communicate()[0].rstrip()
44
45 def get_operator_info():
46     """Returns tuple of (realname, email) of person who is operating
47     this script, as told to use by the Kerberos principal name.
48     Useful for commit messages."""
49     username = get_operator_name()
50     hesinfo = subprocess.Popen(["hesinfo", username, "passwd"],stdout=subprocess.PIPE).communicate()[0]
51     fields = hesinfo.partition(",")[0]
52     realname = fields.rpartition(":")[2]
53     return realname, username + "@mit.edu"
54
55 def get_operator_git():
56     """Returns Real Name <username@mit.edu> suitable for use in
57     Git Something-by: string."""
58     return "%s <%s>" % get_operator_info()
59
60 def get_operator_name():
61     """Returns username of the person operating this script."""
62     principal = os.getenv("SSH_GSSAPI_NAME")
63     if not principal: raise NoOperatorInfo()
64     instance, _, _ = principal.partition("@")
65     if instance.endswith("/root"):
66         username, _, _ = principal.partition("/")
67     else:
68         username = instance
69     return username
70
71 def set_operator_env():
72     try:
73         op_realname, op_email = get_operator_info()
74         os.putenv("GIT_COMMITTER_NAME", op_realname)
75         os.putenv("GIT_COMMITTER_EMAIL", op_email)
76     except NoOperatorInfo:
77         pass
78
79 def set_author_env():
80     try:
81         lockername = get_dir_owner()
82         os.putenv("GIT_AUTHOR_NAME", "%s locker" % lockername)
83         os.putenv("GIT_AUTHOR_EMAIL", "%s@scripts.mit.edu" % lockername)
84     except KeyError:
85         pass
86
87 def set_git_env():
88     set_operator_env()
89     set_author_env()
90
91 def get_git_footer():
92     return "\n".join(["Wizard-revision: %s" % get_revision()
93         ,"Wizard-args: %s" % " ".join(sys.argv)
94         ])
95
96 class Error(wizard.Error):
97     pass
98
99 class NoOperatorInfo(Error):
100     pass
101