2013-04-26 51 views
3

我已經編寫了一套Git插件供工作時在內部使用。它需要在全局模板目錄中安裝一些Git鉤子,但是我在編程方式上找不到Git實際安裝的目錄。我在發現安裝在我們的開發服務器:如何找到安裝Git的目錄?

  • /usr/share/git-core
  • /usr/local/share/git-core
  • /usr/local/git/share/git-core

某些服務器,由於以前的安裝,已經安裝在這些目錄中的一種以上的Git 。我正在尋找一種方法來找出真實的模板目錄,其中git init將複製模板文件。

git init代碼的問題是在copy_templates()

if (!template_dir) 
    template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT); 
if (!template_dir) 
    template_dir = init_db_template_dir; 
if (!template_dir) 
    template_dir = system_path(DEFAULT_GIT_TEMPLATE_DIR); 
if (!template_dir[0]) 
    return; 

然而,當它實際上將要複製的模板,這個代碼僅運行,因此,似乎沒有要找出一個方法是什麼DEFAULT_GIT_TEMPLATE_DIR真的是事先。

我迄今爲止最好的辦法是(僞):

for each possible directory: 
    create a random_filename 
    create a file in the template directory with $random_filename 
    `git init` a new temporary repository 
    check for the existence of $random_filename in the new repo 
    if it exists, we found the real template directory 

這仍然具有建構的「可能的」目錄列表如上的限制。

有沒有更好的方法?

+0

瘋狂。我實現了上述想法,但是在一臺服務器上,root用戶運行'/ usr/bin/git',其他人都在運行'/ usr/local/bin/git',所以它仍然有錯誤的目錄。 – 2013-04-26 04:44:54

+1

我知道這是一個愚蠢的回答,但是在每個git安裝中安裝模板會有什麼危害嗎? – Alan 2013-04-26 04:47:02

+0

@Alan:嗯。當然沒有。好計劃。 – 2013-04-26 04:49:24

回答

1

這是在Python中實現的上述想法。這仍然有可能在$PATH(取決於誰在運行這個)中找到錯誤的git二進制文件,因此在我的特殊情況下,將模板簡單地安裝到我們可以找到的所有模板目錄中會更好(如Alan在上面的評論)。

# This function attempts to find the global git-core directory from 
# which git will copy template files during 'git init'. This is done 
# empirically because git doesn't appear to offer a way to just ask 
# for this directory. See: 
# http://stackoverflow.com/questions/16228558/how-can-i-find-the-directory-where-git-was-installed 
def find_git_core(): 
    PossibleGitCoreDirs = [ 
     "/usr/share/git-core", 
     "/usr/git/share/git-core", 
     "/usr/local/share/git-core", 
     "/usr/local/git/share/git-core", 
    ] 
    possibles = [x for x in PossibleGitCoreDirs if os.path.exists(x)] 
    if not possibles: 
     return None 
    if len(possibles) == 1: 
     return possibles[0] 
    tmp_repo = tempfile.mkdtemp() 
    try: 
     for path in possibles: 
      tmp_file, tmp_name = tempfile.mkstemp(dir=os.path.join(path, "templates")) 
      os.close(tmp_file) 
      try: 
       subprocess.check_call(["git", "init"], env={"GIT_DIR": tmp_repo}) 
       if os.path.exists(os.path.join(tmp_repo, os.path.basename(tmp_name))): 
        return path 
      finally: 
       os.unlink(tmp_name) 
    finally: 
     shutil.rmtree(tmp_repo) 
    return None 
相關問題