Skip to content

Instantly share code, notes, and snippets.

@pahaz pahaz/git_server.py
Created Aug 30, 2014

Embed
What would you like to do?
import os
__author__ = 'pahaz'
from dulwich.server import Backend, UploadPackHandler, ReceivePackHandler
from dulwich.repo import Repo
from dulwich import log_utils
from dulwich.server import (
TCPGitServer,
)
logger = log_utils.getLogger(__name__)
# HOOKS
def post_receive_hook(repo):
print 'HOOK', repo.path
# END HOOKS
HOOKS = {
'post-git-receive-pack': post_receive_hook
}
class ProtocolHooks(object):
name = 'unknown'
def hook(self, name):
global HOOKS
logger.debug('Hook ' + name)
if name in HOOKS:
HOOKS[name](self.repo)
def handle(self):
self.hook('pre-' + self.name)
super(ProtocolHooks, self).handle()
self.hook('post-' + self.name)
class HookedReceivePackHandler(ProtocolHooks, ReceivePackHandler):
name = 'git-receive-pack'
class HookedUploadPackHandler(ProtocolHooks, UploadPackHandler):
name = 'git-upload-pack'
class BaseCommandHandler(object):
def __init__(self, git_backend, cmd_args, protocol):
self.protocol = protocol
self.command_args = cmd_args
self.git_backend = git_backend
def handle(self):
self.protocol.write('Hello! Ok!\n')
self.protocol.write('Off!')
self.protocol.close()
HANDLERS = {
'git-upload-pack': HookedUploadPackHandler,
'git-receive-pack': HookedReceivePackHandler,
'wtf': BaseCommandHandler,
}
class GitBackend(Backend):
def __init__(self, root="."):
super(GitBackend, self).__init__()
self.root = (os.path.abspath(root) + "/").replace("//", "/")
logger.info('GitBackend at {0}'.format(self.root))
def open_repository(self, path):
path = os.path.join(self.root, path.strip('/'))
logger.info('opening repository at {0}'.format(path))
return Repo.init(path, mkdir=True) if not os.path.exists(path) \
else Repo(path)
if __name__ == "__main__":
_path = '.'
_address = '127.0.0.1'
_port = 6889
log_utils.default_logging_config()
backend = GitBackend(_path)
server = TCPGitServer(backend, _address, _port, handlers=HANDLERS)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.