Конвертируйте .gitmodules в синтаксический формат для итерации, используя Bash - PullRequest
0 голосов
/ 22 декабря 2018

Фон

Я хотел бы создать функцию оболочки, которая принимает .gitmodules и выполняет итерацию для каждого модуля, выполняя определенные команды на основе свойств каждого подмодуля (например, <PATH> или <URL> или <BRANCH>).

format Формат по умолчанию .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
}

Ответы [ 2 ]

0 голосов
/ 23 декабря 2018

С небольшой помощью @ phd и Восстановление подмодулей git из .gitmodules (куда меня направил @ phd ), я смог построитьнужная мне функция.

install_submodules()

⚠️ Примечание : Предположим, $REPO_PATH объявлено и инициализировано.

101 Мой ответ - адаптация от https://stackoverflow.com/a/53269641/5290011.

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
}
0 голосов
/ 22 декабря 2018

.gitmodules является .gitconfig -подобным файлом, поэтому вы можете использовать git config для его чтения.Например, прочитайте все значения из .gitmodules, разделите значения по = (ключ = значение) и разделите ключи по .:

git config -f .gitmodules -l | awk '{split($0, a, /=/); split(a[1], b, /\./); print b[1], b[2], b[3], a[2]}'

git config -f .gitmodules -l печатает что-то вроде

submodule.native/inotify_simple.path=native/inotify_simple
submodule.native/inotify_simple.url=https://github.com/chrisjbillington/inotify_simple

и awk вывод будет

submodule native/inotify_simple path native/inotify_simple
submodule native/inotify_simple url https://github.com/chrisjbillington/inotify_simple
...