]> scripts.mit.edu Git - wizard.git/blob - wizard/util.py
Add creation of .scripts/version for easy parallel-find.
[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 dictmap(f, d):
21     """A map function for dictionaries.  Does not allow changing keys, only
22     values"""
23     return dict((k,f(v)) for k,v in d.items())
24
25 def get_exception_name(output):
26     """Reads the stderr output of another Python command and grabs the
27     fully qualified exception name"""
28     lines = output.split("\n")
29     for line in lines[1:]: # skip the "traceback" line
30         line = line.rstrip()
31         if line[0] == ' ': continue
32         if line[-1] == ":":
33             return line[:-1]
34         else:
35             return line
36
37 def get_dir_uid(dir):
38     """Finds the uid of the person who owns this directory."""
39     return os.stat(dir).st_uid
40
41 def get_dir_owner(dir = "."):
42     """Finds the name of the locker this directory is in."""
43     return pwd.getpwuid(get_dir_uid(dir)).pw_name
44
45 def get_revision():
46     """Returns the commit ID of the current Wizard install."""
47     wizard_git = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".git")
48     return subprocess.Popen(["git", "--git-dir=" + wizard_git, "rev-parse", "HEAD"], stdout=subprocess.PIPE).communicate()[0].rstrip()
49
50 def get_operator_info():
51     """Returns tuple of (realname, email) of person who is operating
52     this script, as told to use by the Kerberos principal name.
53     Useful for commit messages."""
54     username = get_operator_name()
55     hesinfo = subprocess.Popen(["hesinfo", username, "passwd"],stdout=subprocess.PIPE).communicate()[0]
56     fields = hesinfo.partition(",")[0]
57     realname = fields.rpartition(":")[2]
58     return realname, username + "@mit.edu"
59
60 def get_operator_git():
61     """Returns Real Name <username@mit.edu> suitable for use in
62     Git Something-by: string."""
63     return "%s <%s>" % get_operator_info()
64
65 def get_operator_name():
66     """Returns username of the person operating this script."""
67     principal = os.getenv("SSH_GSSAPI_NAME")
68     if not principal: raise NoOperatorInfo()
69     instance, _, _ = principal.partition("@")
70     if instance.endswith("/root"):
71         username, _, _ = principal.partition("/")
72     else:
73         username = instance
74     return username
75
76 def set_operator_env():
77     try:
78         op_realname, op_email = get_operator_info()
79         os.putenv("GIT_COMMITTER_NAME", op_realname)
80         os.putenv("GIT_COMMITTER_EMAIL", op_email)
81     except NoOperatorInfo:
82         pass
83
84 def set_author_env():
85     try:
86         lockername = get_dir_owner()
87         os.putenv("GIT_AUTHOR_NAME", "%s locker" % lockername)
88         os.putenv("GIT_AUTHOR_EMAIL", "%s@scripts.mit.edu" % lockername)
89     except KeyError:
90         pass
91
92 def set_git_env():
93     set_operator_env()
94     set_author_env()
95
96 def get_git_footer():
97     return "\n".join(["Wizard-revision: %s" % get_revision()
98         ,"Wizard-args: %s" % " ".join(sys.argv)
99         ])
100
101 class Error(wizard.Error):
102     pass
103
104 class NoOperatorInfo(Error):
105     pass
106