From 947ef68507bf4a6e3eeb160a5cc797278503adc1 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 10 Nov 2013 16:50:54 +0200 Subject: Move git-directory-rewritemap.py script to own dir. --- git-repo-url-rewrite/git-directory-rewritemap.py | 73 ++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100755 git-repo-url-rewrite/git-directory-rewritemap.py (limited to 'git-repo-url-rewrite') diff --git a/git-repo-url-rewrite/git-directory-rewritemap.py b/git-repo-url-rewrite/git-directory-rewritemap.py new file mode 100755 index 0000000..b2c249e --- /dev/null +++ b/git-repo-url-rewrite/git-directory-rewritemap.py @@ -0,0 +1,73 @@ +#!/usr/bin/python -u +# Copyright 2012 Linaro. + +"""Allow accessing .git directories without '.git' in the name. + +To be used with Apache2 mod_rewrite RewriteMap functionality. +This means that "-u" option to python interpreter above is important +for unbuffered output. +""" + +import os + +BASE_PATH = '/srv/gerrit/linaro/git/' + + +def relativize_path(path): + """Ensure `path` does not start with '/'.""" + path = os.path.normpath(path) + if path[0] == os.sep: + path = path[1:] + return path + + +def rewrite_path(base_path, file_path): + """Return a rewritten path with '.git' added where necessary. + + Looks for all the directories with '.git' appended that exist + on disk in `base_path`/`file_path` right-to-left until it finds it. + + Returns None if `file_path` can not be matched, otherwise, + returns a matched file path relative to `base_path`. + """ + file_path = relativize_path(file_path) + full_path = os.path.join(base_path, file_path) + dirname, current = os.path.split(full_path) + filename = None + while current != '': + git_dirname = os.path.join(dirname, current) + # If git_dirname does not exist but a variant with '.git' + # appended does, use the version with '.git' appended. + if (not os.path.isdir(git_dirname) and + os.path.isdir(git_dirname + '.git')): + git_dirname = git_dirname + '.git' + + # None is a special starting value for `filename`: in all + # other cases, it is a string representing the right-hand side + # of the path being looked at. + if filename is not None: + file_path = os.path.join(git_dirname, filename) + filename = os.path.join(current, filename) + else: + file_path = git_dirname + filename = current + + if os.path.exists(file_path): + return os.path.relpath(file_path, base_path) + + dirname, current = os.path.split(dirname) + + return None + + +if __name__ == '__main__': + while True: + request_path = raw_input() + desired_path = rewrite_path(BASE_PATH, request_path) + if desired_path is None: + print request_path + else: + if request_path.startswith(os.sep): + print "/" + desired_path + else: + print desired_path -- cgit v1.2.3