How do I check for valid Git branch names?

前端 未结 6 1715
粉色の甜心
粉色の甜心 2021-01-03 23:40

I\'m developing a git post-receive hook in Python. Data is supplied on stdin with lines similar to

ef4d4037f8568e386629457d4d960915a85da2ae 61a4         


        
6条回答
  •  失恋的感觉
    2021-01-04 00:22

    git check-ref-format with subprocess.Popen is a possibility:

    import subprocess
    process = subprocess.Popen(["git", "check-ref-format", ref])
    exit_status = process.wait()
    

    Advantages:

    • if the algorithm ever changes, the check will update automatically
    • you are sure to get it right, which is way harder with a monster Regex

    Disadvantages:

    • slower because subprocess. But premature optimization is the root of all evil.
    • requires Git as a binary dependency. But in the case of a hook it will always be there.

    pygit2, which uses C bindings to libgit2, would be an even better possibility if check-ref-format is exposed there, as it would be faster than Popen, but I haven't found it.

提交回复
热议问题