代码之家  ›  专栏  ›  技术社区  ›  noisy

是否可以用git别名重写git命令?

  •  43
  • noisy  · 技术社区  · 15 年前

    我的~/.gitconfig是:

    [alias]
            commit = "!sh commit.sh"
    

    但是,当我打字时 GIT提交 ,未调用脚本。

    是可能的,还是我必须使用另一个别名?

    4 回复  |  直到 7 年前
        1
  •  39
  •   Baptiste Pernet    10 年前

    这是不可能的

    这是我克隆的git.git:

    static int run_argv(int *argcp, const char ***argv)
    {
        int done_alias = 0;
    
        while (1) {
            /* See if it's an internal command */
            handle_internal_command(*argcp, *argv);
    
            /* .. then try the external ones */
            execv_dashed_external(*argv);
    
            /* It could be an alias -- this works around the insanity
             * of overriding "git log" with "git show" by having
             * alias.log = show
             */
            if (done_alias || !handle_alias(argcp, argv))
                break;
            done_alias = 1;
        }
    
        return done_alias;
    }
    

    所以这是不可能的。( handle_internal_command 电话 exit 如果找到命令)。

    您可以通过更改行的顺序和 handle_alias 呼叫 出口 如果找到别名。

        2
  •  21
  •   David Mertens    11 年前

    如前所述,不可能使用git别名重写git命令。但是,可以使用shell别名重写git命令。对于任何posixy shell(即非ms cmd )编写一个简单的可执行脚本,执行所需的修改行为并设置外壳别名。在我的 .bashrc (Linux)和 .bash_profile (麦克)我有

    export PATH="~/bin:$PATH"
    ...
    alias git='my-git'
    

    在我的 ~/bin 文件夹我有一个名为 my-git 它检查第一个参数(即git命令)是否 clone . 基本上是这样的:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    my $path_to_git = '/usr/local/bin/git';
    exit(system($path_to_git, @ARGV))
        if @ARGV < 2 or $ARGV[0] ne 'clone';
    # Override git-clone here...
    

    我的有点可配置,但你知道。

        3
  •  17
  •   wjandrea sebs    7 年前

    我选择用bash函数来解决这个问题。如果我打电话 git clone ,它将呼叫重定向到 git cl ,这是我的别名,添加了一些开关。

    function git {
      if [[ "$1" == "clone" && "$@" != *"--help"* ]]; then
        shift 1
        command git cl "$@"
      else
        command git "$@"
      fi
    }
    
        4
  •  14
  •   Ciro Santilli OurBigBook.com    7 年前

    不仅不可能,而且很难

    2009 http://git.661346.n2.nabble.com/allowing-aliases-to-override-builtins-to-support-default-options-td2438491.html

    Hamano replies :

    目前Git不允许别名覆盖内置项。我 理解这背后的原因,但我想知道是否过度 保守的。

    不是这样。

    大多数shell支持用别名覆盖命令,我不确定 为什么Git需要比Shell更保守。

    因为在脚本中使用时,健全的shell不会扩展别名,并且 提供了一种简便的方法,即使在命令行中也能击败别名。

    $ alias ls='ls -aF'
    $ echo ls >script
    $ chmod +x script
    

    并进行比较:

    $ ./script
    $ ls
    $ /bin/ls