Keep a different configuration file (untracked) for each branch

我怕爱的太早我们不能终老 提交于 2020-01-03 17:23:23

问题


In a git repository I have two files: config/conf.yaml.sample (which is tracked by git, but it's ignored when my program is launched) and a copy of it called config/conf.yaml (which is ignored by git, but it's read when my program is launched).

When I switch from branch A to branch B I always have the same configuration file (because config/conf.yaml is untracked) and that means, for example, that each branch relates to the same database, same ports, and so on.

I want to keep a different config/conf.yaml for each branch, so that it changes when switching branches, but I don't want to have git track it (e.g. because it contains the name and password to access the database).

How can I do it?


回答1:


It seems that Git's post-checkout hook is right up your alley:

This hook is invoked when a git checkout is run after having updated the worktree. The hook is given three parameters: the ref of the previous HEAD, the ref of the new HEAD (which may or may not have changed), and a flag indicating whether the checkout was a branch checkout (changing branches, flag=1) or a file checkout (retrieving a file from the index, flag=0). This hook cannot affect the outcome of git checkout.

It is also run after git clone, unless the --no-checkout (-n) option is used. The first parameter given to the hook is the null-ref, the second the ref of the new HEAD and the flag is always 1.

This hook can be used to perform repository validity checks, auto-display differences from the previous HEAD if different, or set working dir metadata properties.

The following script (which must be made executable) should get you started; modify it to suit your needs and save it as .git/hooks/post-checkout:

#!/bin/sh
#
# An example post-checkout hook script to perform an action conditionally on
# the branch (if any) just checked out.
# 
# Test whether a branch was just checked out
if [ "$3" -eq 1 ]; then
    # Save the value of HEAD (do not issue an error if HEAD is detached) 
    symrefHEAD=`git symbolic-ref --quiet HEAD`
    if [  "$symrefHEAD" = "refs/heads/master" ]; then
        # Do something useful for master, e.g.
        # cp config/conf_master.yaml config/conf.yaml
        printf " --- test: You just checked out master. ---\n"
    elif [ "$symrefHEAD" = "refs/heads/develop" ] ; then
        # Do something useful for develop, e.g.
        # cp config/conf_develop.yaml config/conf.yaml
        printf "--- test: You just checked out develop. ---\n"
    else
        # default case
        printf "You just checked out some other branch.\n"
    fi
else
    printf "No branch was checked out\n"
fi


来源:https://stackoverflow.com/questions/25571031/keep-a-different-configuration-file-untracked-for-each-branch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!