什么是git subcommand,如何创建git子命令?

  大多数git用户知道如何在git中创建一个alias以便更便利地使用相关命令。很少有人知道至少不会好好利用的是:你实际上可以为Git创建扩展或者plugin,以便上git完成任何你希望完成的工作。这就是Git subcommand!

  应该如何创建git子命令呢?

1.创建一个shell或者bash脚本来完成你希望它做的工作;

2.将你的脚本文件命名为git-name,这样name就将成为git name中的子命令了!

3.将该脚本放到/usr/local/bin或其他任何$PATH指定的路径中;

4.运行git name命令调用上述脚本

通过上述方法虽然可以创建多个脚本文件来完成一个个小的功能扩展,但是一旦功能变多,则会显得混乱。一个比较好的组织sub command所完成任务的方式是可以将一堆工作脚本通过一个wrapper脚本来整合:

1.创建一个wrapper或者access point

2.为你希望执行的每一个子命令创建一个file/script

3.使用你的wrapper来加载并且运行你的sub-command scripts;

#!/usr/bin/env sh
version() {
    echo "adamcodes git plugin v0.1.0"
    echo
}
usage() {
    echo "usage: git adamcodes <subcommand>"
    echo
    echo "Available subcommands are:"
    echo "hello <name>  Print out Hello World or Hello <name> (if provided)"
}
main() {
    if [ "$#" -lt 1 ]; then  //if the number of options is less than one
        usage; exit 1
    fi

    local subcommand="$1"; shift

    case $subcommand in
        "-h"|"--help")
            usage; exit 0
            ;;
        "-v"|"--version")
            version; exit 0
            ;;
    esac

    export WORKINGDIR=$(dirname "$(echo "$0" | sed -e 's,\,/,g')")
    if [ ! -e "$WORKINGDIR/git-adamcodes-$subcommand" ]; then
        usage; exit 1
    fi

    source "$WORKINGDIR/git-adamcodes-$subcommand"

    if [ ! type "cmd_$subcommand" ]; then
        usage; exit 1
    fi

    cmd_$subcommand "$@"
}

上面内容可以参考: https://adamcod.es/2013/07/12/how-to-create-git-plugin.html

https://adamcod.es/2013/07/19/how-to-create-git-plugin-part2.html

git 子命令在release管理中的应用案例:

在网站的release管理中,可能现在实用的是这样一个流程:

git checkout master
git merge target_branch
git push origin master
git push origin :target_branch

或许你希望通过子命令简化一下上述流程为:

git checkout master
git validate target_branch

这个可以通过创建一个git-validate的脚本文件来实现:

#!/bin/sh

branch=$1
test -z $branch && echo "branch required." 1>&2 && exit 1

git checkout master
git merge $branch
git push origin master
git push origin :$branch

注意:为了实现一个git 子命令,我们并不一定被局限于使用shell脚本来编写代码哦,你可以使用其他比如Ruby,python等更强大的语言来实现@!

http://www.davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/

http://blogs.atlassian.com/2013/04/extending-git/ 

原文地址:https://www.cnblogs.com/kidsitcn/p/4743042.html