是否可以为 Git 中的分支添加别名?

发布于 2024-07-13 20:26:42 字数 439 浏览 11 评论 0原文

我正在考虑大规模使用 Git。 我希望通过调用 master 分支 trunk 来提高采用率并使事情变得更容易。

这可以并且将会给 SVN 用户带来一些安慰。 我知道我可以创建一个名为 trunk 的分支,但这似乎偏离了 Git 规范,可能会导致一些用户感到困惑。

我知道我也可以根据自己的喜好创建和删除标签,但是当我检查这些标签时,它告诉我这是一个非本地分支,这对我来说很好,但可能不是我想要做的。

我是一个完全的 Git 新手,但在发布和构建系统方面是一位经验丰富的专业人士。

我想要做的是能够调用主干线。我已经看到了别名命令的能力 - 这是否也适用于版本化对象的名称?

我知道 git-svn 的存在和其他工具,但分层存储库系统的开销让我感到害怕。

I am looking into using Git on a massive scale. I was hoping to increase adoption and make things easier by calling the master branch trunk.

This can and will give SVN users some feelings of comfort. I know I can create a branch called trunk, but that seems to deviate from the Git norms and might cause some users to get confused.

I know that I can also create and delete tags to my heart's content but when I checkout those tags it tells me it is a non local branch which is just fine with me but probably not what I want to be doing.

I am a total Git newb but a seasoned professional at release and build systems.

What I want to do is to be able to call master trunk. I have seen the ability to alias commands – does this apply for the names of versioned objects as well?

I know git-svn exists and other tools but the overhead of layered repository systems frightens me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦明 2024-07-20 20:26:43

您可以按照 Greg 的建议重命名 master 分支主干,也可以创建一个对 master 分支的符号引用的主干,以便 git 和 svn 用户都拥有他们习惯的“主”分支。

git symbolic-ref refs/heads/trunk refs/heads/master

请注意,Trunk 不是一等公民。 如果您签出 trunk 并执行 git status,您实际上将位于 master 上,但是您可以使用 trunk命令在所有使用分支名称的地方(日志、合并等)。

You can rename the master branch trunk as Greg has suggested, or you can also create a trunk that is a symbolic reference to the master branch so that both git and svn users have the 'main' branch that they are used to.

git symbolic-ref refs/heads/trunk refs/heads/master

Note that trunk isn't a first class citizen. If you checkout trunk and perform a git status you will actually be on master, however you can use the trunk command in all places that you use the branch name (log, merge, etc.).

命硬 2024-07-20 20:26:43

Git 中的“master”这个名字没有什么特别的,只是按照惯例(默认情况下)这么称呼的。 如果您愿意,您当然可以将其称为“trunk”:

git branch -m master trunk

这与 Subversion 非常相似,其中“trunk”这个名称也只是按惯例这么称呼。 您可以在 Subversion 中将主分支称为“master”。

There is nothing special about the name "master" in Git, it's just called that by convention (and by default). You can certainly call it "trunk" if you like:

git branch -m master trunk

This is very much like Subversion, where the name "trunk" is only called that by convention too. You could have called the main branch "master" in Subversion.

网白 2024-07-20 20:26:43

这是查尔斯·贝利的答案中所示技术的安全包装。

$ git branch-alias <alias> <long-and-unwieldy-branch-name> # create alias
$ git branch-alias <alias> # create alias for current branch
$ git branch # view branches and branch aliases
$ git log <alias>
$ git checkout <alias>
$ git push origin <alias> # pushes the branch, not the alias/reference
$ git branch-alias -d <alias> # delete an alias safely
$ git branch-alias -h # help / usage details

请注意,git 版本 2.7.0 - 2.8.2(含)中的一个错误导致“gitbranch”显示“alias -> alias”而不是分支别名的“alias ->branch”。 如果您受到该错误的影响,我建议您升级到 2.8.3 或更高版本。

#!/bin/sh
# git branch-alias
# Author: Phil S.
# Version 1.13.1
version=1.13.1

# Creates branch aliases, so that you can refer to a long branch name
# by a convenient short alias.  This is particularly useful for branch
# names beginning with bug-tracker ID numbers (or similar), where the
# benefits of tab-completion are greatly reduced.

# This is mostly a "do what I mean" wrapper around "git symbolic-ref",
# with numerous safety measures included in order to eliminate the
# (otherwise considerable) risk of trashing a branch if you get your
# arguments wrong.

# Installation:
# Place this script somewhere in your PATH and name it "git-branch-alias"
# and you will be able to invoke it with "git branch-alias" as per the
# following examples.  If you have obtained the script from the git
# mailing list, please see the "Mailing list archives" note below.

# Examples:
# git branch-alias <alias> <long-and-unwieldy-branch-name> # create alias
# git branch-alias <alias> # create alias for current branch
# git branch # view branches and branch aliases
# git log <alias>
# git checkout <alias>
# git push origin <alias> # pushes the branch, not the alias/reference
# git branch-alias -d <alias> # delete an alias safely
# git branch-alias -h # help / usage details

# Caveats:
# Although everything else I've tried works seamlessly, I note that
# git merge <alias> will cause the alias name to be mentioned in the
# commit message, rather than the name of the real branch.  It would
# be nicer if the branch name appeared.

# Compatibility:
# Originally developed with git version 1.7.12.4
# Also tested with git versions 1.9.0, 2.5.4, 2.6.6, 2.8.3
#
# Related git changes between versions 1.7.12.4 and 2.8.3:
# git v1.8.0.1
#  * A symbolic ref refs/heads/SYM was not correctly removed with "git
#    branch -d SYM"; the command removed the ref pointed by SYM
#    instead.
#
# git v1.8.1
#  * "git symbolic-ref" learned the "-d $symref" option to delete the
#    named symbolic ref, which is more intuitive way to spell it than
#    "update-ref -d --no-deref $symref".
#
# git v2.6.5
#  * "git symbolic-ref" forgot to report a failure with its exit status.
#
#  I believe this is commit 3e4068ed90fd3c6f24303560113aae6dbb758699:
#  > symbolic-ref: propagate error code from create_symref()
#  > If create_symref() fails, git-symbolic-ref will still exit with
#  > code 0, and our caller has no idea that the command did nothing.
#  > This appears to have been broken since the beginning of time
#
#  As this affects symref creation only, the sole adverse effect here
#  would be an unintended message to the user if symref creation had
#  actually failed (but not even a misleading one, on account of our
#  reading the reference after its creation, and thus displaying an
#  error if it turned out to be invalid).
#
# git v2.8.3
#  * A change back in version 2.7 to "git branch" broke display of a
#    symbolic ref in a non-standard place in the refs/ hierarchy (we
#    expect symbolic refs to appear in refs/remotes/*/HEAD to point at
#    the primary branch the remote has, and as .git/HEAD to point at the
#    branch we locally checked out).
#
#  This caused "git branch" to display "ref -> ref" instead of "ref -> branch"
#  for branch aliases.  The functionality still works otherwise, but is not
#  nearly so convenient to work with when you cannot trivially see what each
#  alias points to.  This bug affected git versions 2.7.0 - 2.8.2 (inclusive).

# Change log:
# v1.13.1
# Change incorrect uses of git show-ref, introduced by v1.10 (including
# effective regression of v1.08), to use git symbolic-ref instead.
#
# v1.12:
# Fix the option handling for '--', and added it to the help text.
#
# v1.11:
# Minor tidy-ups.  Re-posted to git mailing list:
# https://www.mail-archive.com/git%40vger.kernel.org/msg161274.html
#
# v1.10:
# No longer dependent on refs existing as individual files, as they
# may be packed in .git/packed-refs.
#
# v1.09:
# POSIX-compatible option handling and output.
# Documented an issue with "git branch" in git versions 2.7.0 - 2.8.2.
#
# v1.08:
# Remove test git show-ref --verify --heads --quiet "refs/heads/${symref}"
# for asserting that the specified reference was valid before deleting a
# reference, as we need to permit the deletion of references to branches
# which have /already/ been deleted, and this test prevented that.
# n.b. We already had another validation test to fall back on, using
# git symbolic-ref "refs/heads/${symref}"
#
# v1.07:
# Minor tweaks.  Posted as feature-request to git mailing list:
# https://www.mail-archive.com/git%40vger.kernel.org/msg49171.html

# Mailing list archives:
# If you are reading this via the git mailing list archives at gmane.org
# then this code will probably be broken by an email obfuscation filter
# which automatically converts the symbol '@' to the string ' <at> '.
# Specifically the shell positional parameter expansion "$@" is changed
# to "$ <at> "), so don't try to use the version from gmane.  The copy
# of this message at http://www.mail-archive.com/git%40vger.kernel.org/
# should have the correct code.

command=$(basename $0)
if [ "${command##git-}" != "${command}" ]; then
    command="git ${command##git-}"
fi

# Print argument (and newline) to stdout or stderr.
stdout () {
    printf %s\\n "$1"
}
stderr () {
    printf %s\\n "$1" >&2
}

# Returns the supplied parameters suitably quoted for later evaluation.
quote () {
    for param; do
        printf %s "${param}Z" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/Z\$/' /"
    done
}

# Process option parameters.
parameters=
while [ $# -gt 0 ]; do
    case "$1" in
        ( -- ) {
            shift
            parameters="${parameters}$(quote "$@")"
            break
        };;
        ( -v | --version ) version_help=1; shift;;
        ( -h | --help    ) help=1; shift;;
        ( -d | --delete  ) delete=1; shift;;
        ( -* ) {
            stdout "Invalid option: $1"
            stdout
            shorthelp=1
            shift
        };;
        ( * ) { # non-option parameter
            parameters="${parameters}$(quote "$1")"
            shift
        };;
    esac
done

# Process non-option parameters.
eval "set -- ${parameters}"
symref=$1
branch=$2

# If too few or too many parameters were supplied, display shorthelp.
if [ -z "${symref}" ] || [ -n "$3" ]; then
    shorthelp=1
fi

# If displaying the version, exit immediately.
if [ -n "${version_help}" ]; then
    stdout "${command} version ${version}"
    exit 0
fi

# Don't let short help override long help.
if [ -n "${help}" ]; then
    shorthelp=
fi

# Include the usage summary in both short and long help.
if [ -n "${help}" ] || [ -n "${shorthelp}" ]; then
    cat <<EOF
Usage:
${command} [--] <alias> [<branch>]
${command} (-d | --delete) [--] <alias>
${command} (-v | --version)

EOF
fi

# n.b. Calling "git branch-alias --help" causes git to look for
# a man page for "git-branch-alias", so we shouldn't advertise
# the long option (although we support it if the script is called
# by its real name, rather than via git).
if [ -n "${shorthelp}" ]; then
    cat <<EOF
For help, use: ${command} -h

EOF
    exit 0
fi

# Detailed help.
if [ -n "${help}" ]; then
    cat <<EOF
Creates a symbolic reference <alias> referring to <branch>.
<branch> defaults to the current checked-out branch.

This symbolic reference acts as an alias for <branch>, and can be
used in its place.  More specifically, it WILL be dereferenced to
its target in nearly all situations, so for any given command you
should treat every usage of <alias> as if it were actually <branch>.

If either <alias> or <branch> begins with a hyphen, you can use the
'--' option to prevent subsequent arguments being treated as options.

To safely delete a branch alias, always use:
${command} -d <alias>

WARNING: These symbolic references appear in your branch list as:
 <alias> -> <branch>
and so you might be tempted to try to delete them like a branch:
 git branch -d <alias>

However this can cause problems.  In git versions prior to 1.8.0.1
<alias> will be dereferenced and you will instead delete the
branch it refers to (git will allow this even if you currently
have that branch checked out), and the symbolic reference will
still remain (referencing a branch which is no longer available).

In later versions of git the <alias> will be deleted rather than
the branch; however git will still not check to see whether you
currently have <alias> checked out, and will not prevent you
from deleting it in that situation.  This will leave your HEAD ref
in an invalid state.  Using ${command} -d <alias> resolves
this situation by first switching HEAD to <alias>'s target branch
if HEAD was currently set to <alias>.

EOF
    exit 0
fi

# Confirm the CWD is within a git repository.
#cwd=$(git rev-parse --show-toplevel)
git=$(git rev-parse --git-dir)
if [ $? -ne 0 ]; then
    exit 1
fi

# Use the current branch by default.
if [ -z "${branch}" ]; then
    branch=$(git symbolic-ref -q HEAD)
    if [ $? -ne 0 ]; then
        stderr "Could not establish current HEAD."
        exit 1
    fi
fi

# We expect plain branch names, but also accept the fully-qualified
# (refs/heads/NAME) paths needed by git symbolic-ref; so strip that
# refs/heads/ prefix if it is specified.
branch=${branch##refs/heads/}
symref=${symref##refs/heads/}

# Deleting a symref.
if [ -n "${delete}" ]; then
    # Verify that it IS a symbolic reference.
    if ! git symbolic-ref "refs/heads/${symref}" >/dev/null; then
        stderr "Error validating refs/heads/${symref} as symbolic reference."
        exit 1
    fi

    # If we currently have <symref> checked out, deleting it is bad
    # (as HEAD would no longer be a valid reference).  I believe we do
    # need to inspect the file here, as attempting to read the HEAD
    # reference via git dereferences it to its target branch, and thus
    # we are unable to distinguish between the branch and the symref.
    if grep "^ref: refs/heads/${symref}\$" "${git}/HEAD" >/dev/null 2>&1; then
        stdout "Cannot delete the currently checked out symbolic reference."
        branch=$(git symbolic-ref -q HEAD)
        if [ $? -ne 0 ]; then
            stderr "Could not establish current HEAD."
            exit 1
        fi
        stdout "Switching HEAD to target branch ${branch}"
        # By using git symbolic-ref HEAD to find the target ref
        # and setting HEAD to that target, nothing really changes,
        # but we can now delete the reference safely.
        if ! git symbolic-ref HEAD "${branch}"; then
            stderr "Error updating HEAD from ${symref} to ${branch}"
            stderr "Aborting."
            exit 1
        fi
    fi

    # Delete the reference.
    # git 1.8.1+ provides: git symbolic-ref --delete <symref>
    # but older versions do not include that option, so we use
    # the backwards-compatible command.
    stdout "Deleting symbolic reference refs/heads/${symref}"
    git update-ref -d --no-deref "refs/heads/${symref}"
    exit $?
fi

# Creating a new symbolic reference.

# Error checking.  git symbolic-ref doesn't really do any, and will
# happily mess up your branches; particularly if you get the arguments
# the wrong way around (treating it like ln -s is a really bad idea).
if ! git show-ref --verify --heads --quiet "refs/heads/${branch}"; then
    stderr "Target branch refs/heads/${branch} does not exist."
    exit 1
fi
if target=$(git symbolic-ref -q "refs/heads/${symref}"); then
    stderr "Symbolic reference refs/heads/${symref} already exists:"
    stderr "  ${symref} -> ${target##refs/heads/}"
    stderr "To delete it, use: ${command} -d ${symref}"
    exit 1
elif git show-ref --verify --heads --quiet "refs/heads/${symref}"; then
    stderr "Reference refs/heads/${symref} already exists"
    stderr "(and is not a symbolic reference!)"
    exit 1
fi

# The parameters are good.
# Generate the reference and display the confirmed result.
if git symbolic-ref "refs/heads/${symref}" "refs/heads/${branch}"; then
    target=$(git symbolic-ref "refs/heads/${symref}")
    stdout "  ${symref} -> ${target##refs/heads/}"
else
    stderr "Failed to create branch alias."
    exit 1
fi
# EOF

上游功能请求:
https://www.mail-archive.com/[电子邮件受保护]/msg161274.html

This is a safety wrapper around the technique shown in Charles Bailey's answer.

$ git branch-alias <alias> <long-and-unwieldy-branch-name> # create alias
$ git branch-alias <alias> # create alias for current branch
$ git branch # view branches and branch aliases
$ git log <alias>
$ git checkout <alias>
$ git push origin <alias> # pushes the branch, not the alias/reference
$ git branch-alias -d <alias> # delete an alias safely
$ git branch-alias -h # help / usage details

Please note that a bug in git versions 2.7.0 - 2.8.2 (inclusive) caused "git branch" to display "alias -> alias" instead of "alias -> branch" for branch aliases. I recommend upgrading to 2.8.3 or later if you are affected by that bug.

#!/bin/sh
# git branch-alias
# Author: Phil S.
# Version 1.13.1
version=1.13.1

# Creates branch aliases, so that you can refer to a long branch name
# by a convenient short alias.  This is particularly useful for branch
# names beginning with bug-tracker ID numbers (or similar), where the
# benefits of tab-completion are greatly reduced.

# This is mostly a "do what I mean" wrapper around "git symbolic-ref",
# with numerous safety measures included in order to eliminate the
# (otherwise considerable) risk of trashing a branch if you get your
# arguments wrong.

# Installation:
# Place this script somewhere in your PATH and name it "git-branch-alias"
# and you will be able to invoke it with "git branch-alias" as per the
# following examples.  If you have obtained the script from the git
# mailing list, please see the "Mailing list archives" note below.

# Examples:
# git branch-alias <alias> <long-and-unwieldy-branch-name> # create alias
# git branch-alias <alias> # create alias for current branch
# git branch # view branches and branch aliases
# git log <alias>
# git checkout <alias>
# git push origin <alias> # pushes the branch, not the alias/reference
# git branch-alias -d <alias> # delete an alias safely
# git branch-alias -h # help / usage details

# Caveats:
# Although everything else I've tried works seamlessly, I note that
# git merge <alias> will cause the alias name to be mentioned in the
# commit message, rather than the name of the real branch.  It would
# be nicer if the branch name appeared.

# Compatibility:
# Originally developed with git version 1.7.12.4
# Also tested with git versions 1.9.0, 2.5.4, 2.6.6, 2.8.3
#
# Related git changes between versions 1.7.12.4 and 2.8.3:
# git v1.8.0.1
#  * A symbolic ref refs/heads/SYM was not correctly removed with "git
#    branch -d SYM"; the command removed the ref pointed by SYM
#    instead.
#
# git v1.8.1
#  * "git symbolic-ref" learned the "-d $symref" option to delete the
#    named symbolic ref, which is more intuitive way to spell it than
#    "update-ref -d --no-deref $symref".
#
# git v2.6.5
#  * "git symbolic-ref" forgot to report a failure with its exit status.
#
#  I believe this is commit 3e4068ed90fd3c6f24303560113aae6dbb758699:
#  > symbolic-ref: propagate error code from create_symref()
#  > If create_symref() fails, git-symbolic-ref will still exit with
#  > code 0, and our caller has no idea that the command did nothing.
#  > This appears to have been broken since the beginning of time
#
#  As this affects symref creation only, the sole adverse effect here
#  would be an unintended message to the user if symref creation had
#  actually failed (but not even a misleading one, on account of our
#  reading the reference after its creation, and thus displaying an
#  error if it turned out to be invalid).
#
# git v2.8.3
#  * A change back in version 2.7 to "git branch" broke display of a
#    symbolic ref in a non-standard place in the refs/ hierarchy (we
#    expect symbolic refs to appear in refs/remotes/*/HEAD to point at
#    the primary branch the remote has, and as .git/HEAD to point at the
#    branch we locally checked out).
#
#  This caused "git branch" to display "ref -> ref" instead of "ref -> branch"
#  for branch aliases.  The functionality still works otherwise, but is not
#  nearly so convenient to work with when you cannot trivially see what each
#  alias points to.  This bug affected git versions 2.7.0 - 2.8.2 (inclusive).

# Change log:
# v1.13.1
# Change incorrect uses of git show-ref, introduced by v1.10 (including
# effective regression of v1.08), to use git symbolic-ref instead.
#
# v1.12:
# Fix the option handling for '--', and added it to the help text.
#
# v1.11:
# Minor tidy-ups.  Re-posted to git mailing list:
# https://www.mail-archive.com/git%40vger.kernel.org/msg161274.html
#
# v1.10:
# No longer dependent on refs existing as individual files, as they
# may be packed in .git/packed-refs.
#
# v1.09:
# POSIX-compatible option handling and output.
# Documented an issue with "git branch" in git versions 2.7.0 - 2.8.2.
#
# v1.08:
# Remove test git show-ref --verify --heads --quiet "refs/heads/${symref}"
# for asserting that the specified reference was valid before deleting a
# reference, as we need to permit the deletion of references to branches
# which have /already/ been deleted, and this test prevented that.
# n.b. We already had another validation test to fall back on, using
# git symbolic-ref "refs/heads/${symref}"
#
# v1.07:
# Minor tweaks.  Posted as feature-request to git mailing list:
# https://www.mail-archive.com/git%40vger.kernel.org/msg49171.html

# Mailing list archives:
# If you are reading this via the git mailing list archives at gmane.org
# then this code will probably be broken by an email obfuscation filter
# which automatically converts the symbol '@' to the string ' <at> '.
# Specifically the shell positional parameter expansion "$@" is changed
# to "$ <at> "), so don't try to use the version from gmane.  The copy
# of this message at http://www.mail-archive.com/git%40vger.kernel.org/
# should have the correct code.

command=$(basename $0)
if [ "${command##git-}" != "${command}" ]; then
    command="git ${command##git-}"
fi

# Print argument (and newline) to stdout or stderr.
stdout () {
    printf %s\\n "$1"
}
stderr () {
    printf %s\\n "$1" >&2
}

# Returns the supplied parameters suitably quoted for later evaluation.
quote () {
    for param; do
        printf %s "${param}Z" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/Z\$/' /"
    done
}

# Process option parameters.
parameters=
while [ $# -gt 0 ]; do
    case "$1" in
        ( -- ) {
            shift
            parameters="${parameters}$(quote "$@")"
            break
        };;
        ( -v | --version ) version_help=1; shift;;
        ( -h | --help    ) help=1; shift;;
        ( -d | --delete  ) delete=1; shift;;
        ( -* ) {
            stdout "Invalid option: $1"
            stdout
            shorthelp=1
            shift
        };;
        ( * ) { # non-option parameter
            parameters="${parameters}$(quote "$1")"
            shift
        };;
    esac
done

# Process non-option parameters.
eval "set -- ${parameters}"
symref=$1
branch=$2

# If too few or too many parameters were supplied, display shorthelp.
if [ -z "${symref}" ] || [ -n "$3" ]; then
    shorthelp=1
fi

# If displaying the version, exit immediately.
if [ -n "${version_help}" ]; then
    stdout "${command} version ${version}"
    exit 0
fi

# Don't let short help override long help.
if [ -n "${help}" ]; then
    shorthelp=
fi

# Include the usage summary in both short and long help.
if [ -n "${help}" ] || [ -n "${shorthelp}" ]; then
    cat <<EOF
Usage:
${command} [--] <alias> [<branch>]
${command} (-d | --delete) [--] <alias>
${command} (-v | --version)

EOF
fi

# n.b. Calling "git branch-alias --help" causes git to look for
# a man page for "git-branch-alias", so we shouldn't advertise
# the long option (although we support it if the script is called
# by its real name, rather than via git).
if [ -n "${shorthelp}" ]; then
    cat <<EOF
For help, use: ${command} -h

EOF
    exit 0
fi

# Detailed help.
if [ -n "${help}" ]; then
    cat <<EOF
Creates a symbolic reference <alias> referring to <branch>.
<branch> defaults to the current checked-out branch.

This symbolic reference acts as an alias for <branch>, and can be
used in its place.  More specifically, it WILL be dereferenced to
its target in nearly all situations, so for any given command you
should treat every usage of <alias> as if it were actually <branch>.

If either <alias> or <branch> begins with a hyphen, you can use the
'--' option to prevent subsequent arguments being treated as options.

To safely delete a branch alias, always use:
${command} -d <alias>

WARNING: These symbolic references appear in your branch list as:
 <alias> -> <branch>
and so you might be tempted to try to delete them like a branch:
 git branch -d <alias>

However this can cause problems.  In git versions prior to 1.8.0.1
<alias> will be dereferenced and you will instead delete the
branch it refers to (git will allow this even if you currently
have that branch checked out), and the symbolic reference will
still remain (referencing a branch which is no longer available).

In later versions of git the <alias> will be deleted rather than
the branch; however git will still not check to see whether you
currently have <alias> checked out, and will not prevent you
from deleting it in that situation.  This will leave your HEAD ref
in an invalid state.  Using ${command} -d <alias> resolves
this situation by first switching HEAD to <alias>'s target branch
if HEAD was currently set to <alias>.

EOF
    exit 0
fi

# Confirm the CWD is within a git repository.
#cwd=$(git rev-parse --show-toplevel)
git=$(git rev-parse --git-dir)
if [ $? -ne 0 ]; then
    exit 1
fi

# Use the current branch by default.
if [ -z "${branch}" ]; then
    branch=$(git symbolic-ref -q HEAD)
    if [ $? -ne 0 ]; then
        stderr "Could not establish current HEAD."
        exit 1
    fi
fi

# We expect plain branch names, but also accept the fully-qualified
# (refs/heads/NAME) paths needed by git symbolic-ref; so strip that
# refs/heads/ prefix if it is specified.
branch=${branch##refs/heads/}
symref=${symref##refs/heads/}

# Deleting a symref.
if [ -n "${delete}" ]; then
    # Verify that it IS a symbolic reference.
    if ! git symbolic-ref "refs/heads/${symref}" >/dev/null; then
        stderr "Error validating refs/heads/${symref} as symbolic reference."
        exit 1
    fi

    # If we currently have <symref> checked out, deleting it is bad
    # (as HEAD would no longer be a valid reference).  I believe we do
    # need to inspect the file here, as attempting to read the HEAD
    # reference via git dereferences it to its target branch, and thus
    # we are unable to distinguish between the branch and the symref.
    if grep "^ref: refs/heads/${symref}\$" "${git}/HEAD" >/dev/null 2>&1; then
        stdout "Cannot delete the currently checked out symbolic reference."
        branch=$(git symbolic-ref -q HEAD)
        if [ $? -ne 0 ]; then
            stderr "Could not establish current HEAD."
            exit 1
        fi
        stdout "Switching HEAD to target branch ${branch}"
        # By using git symbolic-ref HEAD to find the target ref
        # and setting HEAD to that target, nothing really changes,
        # but we can now delete the reference safely.
        if ! git symbolic-ref HEAD "${branch}"; then
            stderr "Error updating HEAD from ${symref} to ${branch}"
            stderr "Aborting."
            exit 1
        fi
    fi

    # Delete the reference.
    # git 1.8.1+ provides: git symbolic-ref --delete <symref>
    # but older versions do not include that option, so we use
    # the backwards-compatible command.
    stdout "Deleting symbolic reference refs/heads/${symref}"
    git update-ref -d --no-deref "refs/heads/${symref}"
    exit $?
fi

# Creating a new symbolic reference.

# Error checking.  git symbolic-ref doesn't really do any, and will
# happily mess up your branches; particularly if you get the arguments
# the wrong way around (treating it like ln -s is a really bad idea).
if ! git show-ref --verify --heads --quiet "refs/heads/${branch}"; then
    stderr "Target branch refs/heads/${branch} does not exist."
    exit 1
fi
if target=$(git symbolic-ref -q "refs/heads/${symref}"); then
    stderr "Symbolic reference refs/heads/${symref} already exists:"
    stderr "  ${symref} -> ${target##refs/heads/}"
    stderr "To delete it, use: ${command} -d ${symref}"
    exit 1
elif git show-ref --verify --heads --quiet "refs/heads/${symref}"; then
    stderr "Reference refs/heads/${symref} already exists"
    stderr "(and is not a symbolic reference!)"
    exit 1
fi

# The parameters are good.
# Generate the reference and display the confirmed result.
if git symbolic-ref "refs/heads/${symref}" "refs/heads/${branch}"; then
    target=$(git symbolic-ref "refs/heads/${symref}")
    stdout "  ${symref} -> ${target##refs/heads/}"
else
    stderr "Failed to create branch alias."
    exit 1
fi
# EOF

Upstream feature request:
https://www.mail-archive.com/[email protected]/msg161274.html

烟雨扶苏 2024-07-20 20:26:43

Tes,使用 git symbolic-ref;

git symbolic-ref refs/heads/trunk refs/heads/master
git symbolic-ref refs/heads/master refs/heads/main

但是“当前分支”(gitbranch --show-current)将是“不正确的”(仍会显示目标分支而不是别名分支):

在 Git 2.39(2022 年第 4 季度)之前,在检查了指向另一个分支的符号引用“分支”后,“git symbolic-ref HEAD"(man) 报告底层分支,而不是用户作为参数给出 checkout 的符号引用。

该命令学习了“--no-recurse”选项,仅在取消引用symbolic-ref一次后停止。

请参阅提交 b77e3bd(2022 年 10 月 7 日),作者:Junio C Hamano (gitster)
(由 Junio C Hamano -- gitster -- 合并于 提交 4a48c7d,2022 年 10 月 21 日)

symbolic-ref:教导“-- [无-]递归”选项

假设您正在管理项目中的许多维护跟踪,其中一些较新的维护跟踪是 maint-2.36maint-2.37
进一步想象一下,您的项目最近标记了官方 2.38 版本,这意味着您需要尽快启动 maint-2.38 跟踪,方法是:

$ git checkout -b maint-2.38 v2.38.0^0 
  $ git 分支 --list 'maint-2.3[6-9]' 
  * 维护-2.38  
    维护-2.36  
    维护-2.37   
  

到目前为止,一切顺利。
但是,希望不必担心哪个维护轨道是最新的也是合理的,通过将一个听起来更通用的“maint”分支指向它,通过执行以下操作:

$ git symbolic-ref refs/heads/maint refs/heads/maint-2.38 
  

这将允许你说“无论它是什么,检查最新的维护跟踪”,通过执行以下操作:

$ git checkout 维护 
  $ git 分支 --显示当前 
  维护-2.38 
  

可以说我们在“maint-2.38”上而不是在“maint”上更好,并且 git merge/pull 会记录到 maint-2.38 而不是 maint,所以我认为我们拥有的是一个很好的行为。

然而,有一点有点令人恼火,我认为没有一个好的方法(除了“cat .git/HEAD”之外)来了解您签出了“maint”以进入该状态。< br>
就像“git分支的输出 - -show-current"(man) 上面显示,“git symbolic-ref"(man) HEAD 将报告 'refs/heads/maint-2.38',绕过指向 'refs/heads/maint' 的中间符号引用位于 HEAD 处。

内部 resolve_ref() API 已经提供了在解析单个级别的符号引用后停止的必要支持,我们可以通过添加“--[no-]recurse”来公开它" 命令的选项。

git symbolic-ref 现在包含在其 手册页

 'git symbolic-ref' [-q] [--short] [--no-recurse] ; 
  

--递归

--无递归

当将 的值显示为符号引用时,如果
引用另一个符号引用,遵循这样的链
符号引用,直到结果不再指向
符号引用(--recurse,这是默认值)。
--no-recurse 仅取消引用单个级别后停止
符号引用。

Tes, using git symbolic-ref <alias-branch> <targetbranch>:

git symbolic-ref refs/heads/trunk refs/heads/master
git symbolic-ref refs/heads/master refs/heads/main

Hut the "current branch" (git branch --show-current) would be "incorrect" (would still show the target branch instead of your alias branch):

Before Git 2.39 (Q4 2022), after checking out a "branch" that is a symbolic-ref that points at another branch, "git symbolic-ref HEAD"(man) reports the underlying branch, not the symbolic-ref the user gave checkout as argument.

The command learned the "--no-recurse" option to stop after dereferencing a symbolic-ref only once.

See commit b77e3bd (07 Oct 2022) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 4a48c7d, 21 Oct 2022)

symbolic-ref: teach "--[no-]recurse" option

Suppose you are managing many maintenance tracks in your project, and some of the more recent ones are maint-2.36 and maint-2.37.
Further imagine that your project recently tagged the official 2.38 release, which means you would need to start maint-2.38 track soon, by doing:

$ git checkout -b maint-2.38 v2.38.0^0
$ git branch --list 'maint-2.3[6-9]'
* maint-2.38 
  maint-2.36 
  maint-2.37  

So far, so good.
But it also is reasonable to want not to have to worry about which maintenance track is the latest, by pointing a more generic-sounding 'maint' branch at it, by doing:

$ git symbolic-ref refs/heads/maint refs/heads/maint-2.38

which would allow you to say "whichever it is, check out the latest maintenance track", by doing:

$ git checkout maint
$ git branch --show-current
maint-2.38

It is arguably better to say that we are on 'maint-2.38' rather than on 'maint', and git merge/pull would record into maint-2.38 and not into maint, so I think what we have is a good behaviour.

One thing that is slightly irritating, however, is that I do not think there is a good way (other than "cat .git/HEAD") to learn that you checked out 'maint' to get into that state.
Just like the output of "git branch --show-current"(man) shows above, "git symbolic-ref"(man) HEAD would report 'refs/heads/maint-2.38', bypassing the intermediate symbolic ref at 'refs/heads/maint' that is pointed at by HEAD.

The internal resolve_ref() API already has the necessary support for stopping after resolving a single level of a symbolic-ref, and we can expose it by adding a "--[no-]recurse" option to the command.

git symbolic-ref now includes in its man page:

 'git symbolic-ref' [-q] [--short] [--no-recurse] <name>

--recurse

--no-recurse

When showing the value of as a symbolic ref, if
refers to another symbolic ref, follow such a chain
of symbolic refs until the result no longer points at a
symbolic ref (--recurse, which is the default).
--no-recurse stops after dereferencing only a single level
of symbolic ref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文