Determine if directory is under git control

后端 未结 10 1374
醉酒成梦
醉酒成梦 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 13:07

    If you'd prefer to look for a .gitdirectory, here's a cute way of doing that in Ruby:

    require 'pathname'
    
    def gitcheck()
      Pathname.pwd.ascend {|p| return true if (p + ".git").directory? }
      false
    end
    

    I'm unable to find something similar to ascend in Python.

    0 讨论(0)
  • 2021-01-30 13:09

    With gitpython, you can make a function like this:

    import git
    
    ...
    
    def is_git_repo(path):
        try:
            _ = git.Repo(path).git_dir
            return True
        except git.exc.InvalidGitRepositoryError:
            return False
    
    0 讨论(0)
  • 2021-01-30 13:16

    It is hard to define what a .git/ repository is

    I did a bit of experimenting to see what Git considers as a Git repository.

    As of 1.9.1, the minimal directory structure that must be inside a .git directory for Git to consider it is:

    mkdir objects refs
    printf 'ref: refs/' > HEAD
    

    as recognized by rev-parse.

    It is also obviously a corrupt repository in which most useful commands will fail.

    The morale is: like any other format detection, false positives are inevitable, specially here that the minimal repo is so simple.

    If you want something robust, instead of detecting if it is a Git repo, try to do whatever you want to do, and raise errors and deal with them if it fails.

    It's easier to ask forgiveness than it is to get permission.

    0 讨论(0)
  • 2021-01-30 13:20

    Add this to your .bash_profile, and your prompt will always show the active git branch and whether you have uncommitted changes.

    function parse_git_dirty {
      [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit (working directory clean)" ]] && echo "*"
    }
    function parse_git_branch {
      git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/[\1$(parse_git_dirty)]/"
    }
    
    export PS1=' \[\033[0;33m\]\w\[\033[00m\]\[\033[01;00m\]$(parse_git_branch): ' #PS1='\w> '
    

    You'll see this:

     ~: 
     ~: cd code/scala-plugin/
     ~/code/scala-plugin[master*]: 
    
    0 讨论(0)
提交回复
热议问题