Can a git-controlled file be aware of which branch it belongs to?

前端 未结 3 1068
礼貌的吻别
礼貌的吻别 2020-12-19 23:41

Maybe it might be a strange need, but I believe it would be helpful to have something like this:

if($branch$ === \"master) {
   // Special code for the maste         


        
相关标签:
3条回答
  • 2020-12-20 00:11

    No, all meta file information is stored under .git in the root directory. You can detect the current branch with the following bash command (code modified, but originally found here):

    function parse_git_branch() {
      git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1/"
    }
    
    0 讨论(0)
  • 2020-12-20 00:12

    If you need that information in hooks, the usual way is to not rely on a porcelain command, but on plumbing ones:

    #!/bin/sh
    branch=$(git rev-parse --symbolic --abbrev-ref HEAD)
    
    0 讨论(0)
  • 2020-12-20 00:22

    Git has not keyword expansion but Git has filters:

    You would set up a smudge filter that gets run every time you checkout the file to your working copy. In this filter, you can check the current branch and do some magic stuff in your sources (original images taken from (outdated) http://git-scm.com/book/ch7-2.html, now http://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Keyword-Expansion):

    enter image description here

    You would also set up a clean filter that gets run every time the file is staged:

    enter image description here

    Of course, you would set up the filter not for ALL files you're using but only for a single one that gets included by the other files of your project.

    This would be the Git way to do what you want.

    0 讨论(0)
提交回复
热议问题