使用Bash将.gitmodules转换为可解析的格式以进行迭代 [英] Convert .gitmodules into a parsable format for iteration using Bash

查看:167
本文介绍了使用Bash将.gitmodules转换为可解析的格式以进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个外壳函数,它使用.gitmodules并根据每个子模块的属性(例如<PATH><URL><BRANCH>)遍历每个执行某些命令的模块.

I would like to make a shell function that takes .gitmodules and iterates over each module executing certain commands based off of each submodules properties (e.g. <PATH> or <URL> or <BRANCH>).

➡️.gitmodules的默认格式:

[submodule "PATH"]
    path = <PATH>
    url = <URL>
[submodule "PATH"]
    path = <PATH>
    url = <URL>
    branch = <BRANCH>

➡️伪代码:

def install_modules() {
    modules = new list

    fill each index of the modules list with each submodule & its properties

    iteratate over modules
       if module @ 'path' contains a specified 'branch':
          git submodule add -b 'branch' 'url' 'path'
       else:
          git submodule add 'url' 'path'
}

⚠️当前install_modules()

# currently works for grabbing the first line of the file
# doesn't work for each line after.
install_modules() {
    declare -A regex

    regex["module"]='\[submodule "(.*)"\]'
    regex["url"]='url = "(.*)"'
    regex["branch"]='branch = "(.*)"'

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    cat < ".gitmodules" | while read -r LINE; do
        if [[ $LINE =~ ${regex[module]} ]]; then
            PATH=${BASH_REMATCH[1]}

            echo "$PATH"
        fi
    done
}

推荐答案

@phd 从.gitmodules 恢复git子模块(其中 @phd 指向我),我能够构造所需的功能.

With a little help from @phd and Restore git submodules from .gitmodules (which @phd pointed me towards), I was able to construct the function that I needed.

⚠️注意:假设$REPO_PATH被声明为&初始化.

⚠️ Note: Assume $REPO_PATH is declared & initialized.

⚠️我的答案是对 https://stackoverflow.com/a/53269641/5290011的改编./em>

install_submodules() {
    git -C "${REPO_PATH}" config -f .gitmodules --get-regexp '^submodule\..*\.path$' |
        while read -r KEY MODULE_PATH
        do
            # If the module's path exists, remove it.
            # This is done b/c the module's path is currently 
            # not a valid git repo and adding the submodule will cause an error.
            [ -d "${MODULE_PATH}" ] && sudo rm -rf "${MODULE_PATH}"

            NAME="$(echo "${KEY}" | sed 's/^submodule\.\(.*\)\.path$/\1/')"

            url_key="$(echo "${KEY}" | sed 's/\.path$/.url/')"
            branch_key="$(echo "${KEY}" | sed 's/\.path$/.branch/')"

            URL="$(git config -f .gitmodules --get "${url_key}")"
            BRANCH="$(git config -f .gitmodules --get "${branch_key}" || echo "master")"

            git -C "${REPO_PATH}" submodule add --force -b "${BRANCH}" --name "${NAME}" "${URL}" "${MODULE_PATH}" || continue
        done

    git -C "${REPO_PATH}" submodule update --init --recursive
}

这篇关于使用Bash将.gitmodules转换为可解析的格式以进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆