Determine if directory is under git control

后端 未结 10 1395
醉酒成梦
醉酒成梦 2021-01-30 12:25

How can I tell if a given directory is part of a git respository?

(The following is in python, but bash or something would be fine.)

os.path.isdir(\'.svn         


        
10条回答
  •  醉酒成梦
    2021-01-30 12:57

    Using git rev-parse --is-inside-work-tree along with subprocess.Popen, you can check if "true" is printed from the output indicating the directory does have a git repo:

    import subprocess
    
    repo_dir = "../path/to/check/" 
    
    command = ['git', 'rev-parse', '--is-inside-work-tree']
    process = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=repo_dir,
                               universal_newlines=True)
    process_output = process.communicate()[0]
    
    is_git_repo = str(process_output.strip())
    
    if is_git_repo == "true":
        print("success! git repo found under {0}".format(repo_dir))
    else:
        print("sorry. no git repo found under {0}".format(repo_dir))
    

提交回复
热议问题