1
0
Fork 0
bash_scripts/all_repo_create.sh
2025-02-13 16:17:05 +03:00

96 lines
6.5 KiB
Bash
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
echo "Создание репозиториев и отправка данных на сервер 'git.org.ru'."
#-----------------------------------------------------------------------------------------------;
prompt="Подтверждение (да/нет): " && read -erp "$prompt" line && echo -ne "\033[1A$prompt\033[K"
case "${line,,}" in y | yes | д | да) echo "ПОДТВЕРЖДЕНИЕ" ;; *) echo "ОТМЕНА" && exit 0 ;; esac
#-----------------------------------------------------------------------------------------------;
export domain="git.org.ru"
export owner="music"
export user="golovin"
export token && token="$(cat ".token")"
export basedir="$PWD"
export bash="$PWD/avatars/bash.jpg"
export music="$PWD/avatars/music.jpg"
export time_ms && time_ms="$(date '+%s%3N')"
#-----------------------------------------------------------------------------------------------;
# вывести строку текста в консоль и дописать в конец файла
function info_log { case "$2" in "") echo_tee "$(tee)" "$1" ;; *) echo_tee "$1" "$2" ;; esac }
function echo_tee { echo "$1" | tee -a "$basedir/logs/$domain.$2.log"; }
#-----------------------------------------------------------------------------------------------;
# создание репозиториев
function repo_create {
repo="${1##*/}"
cd "$repo" || return 1
#-----------------------------------------------------------------------------------------------;
heading+=("1. Вызываем API сервера Gitea и пересоздаём удалённый репозиторий на сервере.")
heading+=("2. Пересоздаём локальный репозиторий git и отправляем данные на сервер Gitea.")
#-----------------------------------------------------------------------------------------------;
avatar="$music"
case "$repo" in
"bash_scripts") description="Управление процессами" && avatar="$bash" ;;
"compilation") description="Случайный порядок / 44 MHz / 128 Kbps" ;;
*) return ;; # никаких лишних каталогов
esac
avatar="$(basenc "$avatar" --base64 -w0)"
#-----------------------------------------------------------------------------------------------;
while true; do
printf '%s\n' "${heading[@]}" >"$basedir/logs/$domain.$repo.log"
info_log "Удаление старого репозитория на сервере" "$repo"
curl -i -X DELETE "https://$domain/api/v1/repos/$owner/$repo" \
-H "Authorization: token $token" \
-H "Accept: application/json" | info_log "$repo"
info_log "Создание нового репозитория пользователя." "$repo"
curl -i -X POST "https://$domain/api/v1/user/repos" \
-H "Authorization: token $token" \
-H "Accept: application/json" \
-H "Content-Type: application/json" -d "{
\"name\": \"$repo\", \"description\": \"$description\" }" | info_log "$repo"
info_log "Перемещение репозитория в группу." "$repo"
curl -i -X POST "https://$domain/api/v1/repos/$user/$repo/transfer" \
-H "Authorization: token $token" \
-H "Accept: application/json" \
-H "Content-Type: application/json" -d "{ \"new_owner\": \"$owner\" }" | info_log "$repo"
info_log "Изменение свойств репозитория / отключение ненужного" "$repo"
curl -i -X PATCH "https://$domain/api/v1/repos/$owner/$repo" \
-H "Authorization: token $token" \
-H "Accept: application/json" \
-H "Content-Type: application/json" -d "{
\"has_projects\": false, \"has_issues\": false,
\"has_releases\": false, \"has_actions\": false,
\"has_packages\": false, \"has_pull_requests\": false,
\"has_wiki\": false }" | info_log "$repo"
info_log "Добавление аватарки для репозитория" "$repo"
curl -i -X POST "https://$domain/api/v1/repos/$owner/$repo/avatar" \
-H "Authorization: token $token" \
-H "Accept: application/json" \
-H "Content-Type: application/json" -d "{ \"image\": \"$avatar\" }" | info_log "$repo"
#-----------------------------------------------------------------------------------------------;
# проверка корректности ответов от сервера при создании репозитория
case "$(tail -n+10 "$basedir/logs/$domain.$repo.log" | grep -cE '^HTTP/[1,2].{,2}? [4,5]')" in
0) break ;; *) echo "Ошибка 400-500 при подключении к серверу: $repo" ;;
esac
done
#-----------------------------------------------------------------------------------------------;
info_log "Получение списка файлов для репозитория" "$repo"
readarray -t file_array <"$basedir/repo_list/$repo.txt" || return 1
#-----------------------------------------------------------------------------------------------;
info_log "Пересоздание локального репозитория и отправка данных на сервер" "$repo"
rm -rf ".git" # удаление старого репозитория
git init -b "master" | grep -E '\S' | info_log "$repo"
git remote add "$domain" "git@$domain:$owner/$repo.git"
git add --all
git commit ".git*" -m "Инициализация" | info_log "$repo"
git commit "*.md" -m "Описание" | info_log "$repo"
printf '%s\n' "${file_array[@]/*.md*/}" | grep '\S' |
sed -r 's/^(.*);(.*)$/git commit "\1" -m "\2"/' |
xargs -L1 -d'\n' -P1 bash -c | info_log "$repo"
git push -u "$domain" "master" | info_log "$repo"
#-----------------------------------------------------------------------------------------------;
# замер продолжительности выполнения в миллисекундах, пересчёт в минуты, секунды и миллисекунды
tms="$(($(date '+%s%3N') - time_ms))" && min="$((tms / 1000 / 60))" && sec="$((tms / 1000 % 60))"
ms="$((tms % 1000))" && printf 'Общее время выполнения: %02d:%02d.%03d мс.' "$min" "$sec" "$ms" | info_log "$repo"
}
export -f repo_create info_log echo_tee
cd .. # выход из репозитория
# запуск параллельной обработки всех репозиториев, расположенных на одном уровне с текущим, кроме папки ".idea"
find . -mindepth 1 -maxdepth 1 -type d -not -name ".idea" -printf 'repo_create "%h/%f"\0' | xargs -n1 -0 -P0 bash -c