1#!/usr/bin/env python
2#
3# Original author: Richard Bateman <taxilian@gmail.com>
4#
5# Any questions or concerns about how this works should be addressed to
6# me, not to sitaram. Please note that neither I nor sitaram make any
7# guarantees about the security or usefulness of this script. It may
8# be used without warantee or any guarantee of any kind.
9#
10# This script is licensed under the New BSD license
11# Copyright 2011 Richard Bateman
12#
13
14import sys, os, subprocess
15
16class gitolite(object):
17    def __init__(self, **kvargs):
18        self.GL_BINDIR = kvargs["GL_BINDIR"] if "GL_BINDIR" in kvargs else os.environ["GL_BINDIR"]
19        self.user = kvargs["GL_USER"] if "GL_USER" in kvargs else os.environ["GL_USER"]
20        pass
21
22    def gitolite_execute(self, command, std_inputdata = None):
23        cmd = "perl -I%s -Mgitolite -e '%s'" % (self.GL_BINDIR,command)
24        p = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE)
25        stdout, stderr = p.communicate(std_inputdata)
26        if p.returncode is not 0:
27            raise Exception(stderr)
28        return stdout.strip()
29
30    def run_custom_command(self, repo, user, command, extra = None):
31        os.environ["SSH_ORIGINAL_COMMAND"] = "%s %s" % (command, repo)
32        return self.gitolite_execute('run_custom_command("%s")' % user, extra)
33
34    def get_perms(self, repo, user):
35        full = self.run_custom_command(repo, user, "getperms")
36        plist = full.split("\n")
37        perms = {}
38        for line in plist:
39            if line == "":
40                continue
41            var, strlist = line.split(" ", 1)
42            perms[var] = strlist.split(" ")
43
44        return perms
45
46    def set_perms(self, repo, user, perms):
47        permstr = ""
48        for var, curlist in perms.iteritems():
49            if len(curlist) == 0:
50                continue;
51            varstr = var
52            for cur in curlist:
53                varstr += " %s" % cur
54            permstr = permstr + "\n" + varstr
55        resp = self.run_custom_command(repo, user, "setperms", permstr.strip())
56
57    def valid_owned_repo(self, repo, user):
58        rights, user = self.get_rights_and_owner(repo, user)
59        return owner == user
60
61    def get_rights_and_owner(self, repo, user):
62        if not repo.endswith(".git"):
63            repo = "%s.git" % repo
64        ans = self.gitolite_execute('cli_repo_rights("%s")' % repo)
65        perms, owner = ans.split(" ")
66        rights = {"Read": "R" in perms, "Write": "W" in perms, "Create": "C" in perms}
67        return rights, owner
68
69if __name__ == "__main__":
70    if "GL_USER" not in os.environ:
71        raise "No user!"
72    user = os.environ["GL_USER"]
73    repo = sys.argv[1]
74
75    gl = gitolite()
76    print gl.get_rights_and_owner(repo, user)
77    print gl.get_perms(repo, user)
78