#!/usr/bin/env python
import re, sys, os
from stat import *
import getpass, grp
def usage():
usage_str = "Usage: " + sys.argv[0] + """[--no-grades]
You must be in to execute this.
looks up each file and subdirectory under
/spool
owned by the user, and changes its group to the grades group name. It
also makes the file group readable, writeable, and if a directory,
executable and with the setgid bit and sticky bit.
If the option --no-grades is there, files with name
beginning with GRADE- will not be changed: maybe you do not want to make
the grades visible yet.
"""
sys.stderr.write(usage_str)
sys.exit(1)
def ch_grpown_dir(path, uid, gid, grades, prefix):
"""Change the group ownership in the directory tree under path.
ARGS:
prefix helps in displaying the tree during the recursive calls."""
if re.match("^GRADE-", os.path.basename(path)) and not grades: return
print prefix, os.path.basename(path)
try:
stat_return = os.lstat(path)
except OSError, detail:
sys.stderr.write("lstat " + path + " failed: " +
detail.strerror + "\n")
return
if uid == stat_return[ST_UID]:
if gid != stat_return[ST_GID]:
try:
os.chown(path, uid, gid)
except OSError, detail:
sys.stderr.write("chown " + path + " failed: " +
detail.strerror + "\n")
return
mode = stat_return[ST_MODE]
newmode = mode & 0777
if os.path.isdir(path): # or # if ST_ISDIR(mode):
try:
os.chmod(path, newmode | 03070)
except OSError, detail:
sys.stderr.write("chmod " + path + " failed: " +
detail.strerror + "\n")
return
else:
if "HEADER" != os.path.basename(path):
try:
os.chmod(path, newmode | 0060)
except OSError, detail:
sys.stderr.write("chmod " + path + " failed: " +
detail.strerror + "\n")
return
if os.path.isdir(path):
try:
dirlist = os.listdir(path)
except OSError, detail:
sys.stderr.write("os.listdir(" + path + ") failed: " +
detail.strerror + "\n")
return
for file in dirlist:
ch_grpown_dir(os.path.join(path, file), uid, gid, grades,
prefix + " ")
"main"
argc = len(sys.argv)
if 2 < argc : usage()
grades = 1
if 2 == argc:
if "--no-grades" != sys.argv[1]: usage()
else: grades = 0
logname = getpass.getuser() # Not really used.
print "Login name: ", logname
uid = os.getuid()
# cwd = /cs/course/cs410/homework
spool = os.path.join(os.getcwd(), "spool");
sys.stderr.write("Spool directory: " + spool + "\n")
try:
stat_return = os.lstat(spool)
except OSError, detail:
sys.stderr.write("lstat " + spool + " failed: " +
detail.strerror + "\n")
exit(1)
gid = stat_return[ST_GID]
try:
gname = grp.getgrgid(gid)[0] # Not really used.
except OSError, detail:
sys.stderr.write("getgrgid" + gid + " failed: " +
detail.strerror + "\n")
exit(1)
print "Group name: ", gname
ch_grpown_dir(spool, uid, gid, grades, "")