%h - %an, %ar : %s" "HEAD..${after_sha}")
+ COMPARE_HASH="${after_sha}"
+ else
+ # Читаем вывод git log в массив
+ mapfile -t readarray < <(git log --pretty=format:"%h - %an, %ar : %s" "${before_sha}..${after_sha}")
+ COMPARE_HASH="${before_sha}..${after_sha}"
+ fi
+
+ TOTAL_COMMITS=${#readarray[@]}
+
+ if [ "$TOTAL_COMMITS" -eq 1 ]; then
+ COMMITS_TEXT="$TOTAL_COMMITS new commit"
+ else
+ COMMITS_TEXT="$TOTAL_COMMITS new commits"
+ fi
+
+ # Подготовка заголовка
+ HEADER="[${repository_name}:${ref_name}] $COMMITS_TEXT by ${actor}"
+
+ # Создаем временную директорию для сообщений
+ mkdir -p ./tmp_messages || { echo "Error: Failed to create tmp_messages directory" >&2; return 1; }
+
+ # Разбиваем сообщение на части по количеству символов
+ PART_INDEX=0
+ CHUNK="$HEADER\n\n"
+ CURRENT_LENGTH=${#CHUNK}
+
+ # Максимальная длина для одного коммита (с учетом заголовка и отступов)
+ local MAX_COMMIT_LENGTH=$((MAX_LENGTH - ${#HEADER} - 2))
+
+ for COMMIT in "${readarray[@]}"; do
+ # Добавляем перевод строки к коммиту
+ COMMIT_WITH_NEWLINE="$COMMIT\n"
+ COMMIT_LENGTH=${#COMMIT_WITH_NEWLINE}
+
+ # Проверяем длину коммита
+ if [ $COMMIT_LENGTH -gt $MAX_COMMIT_LENGTH ]; then
+ echo "Warning: Commit message is too long and will be truncated" >&2
+ # Обрезаем коммит с учетом места под эллипсис
+ COMMIT_WITH_NEWLINE="${COMMIT_WITH_NEWLINE:0:$((MAX_COMMIT_LENGTH - ELLIPSIS_LENGTH))} ...\n"
+ COMMIT_LENGTH=${#COMMIT_WITH_NEWLINE}
+ fi
+
+ # Проверяем, поместится ли следующий коммит
+ if ((CURRENT_LENGTH + COMMIT_LENGTH > MAX_LENGTH)); then
+ # Сохраняем текущий чанк
+ printf "%b" "$CHUNK" > "./tmp_messages/part_${PART_INDEX}.txt" || { echo "Error: Failed to write to file" >&2; return 1; }
+ PART_INDEX=$((PART_INDEX + 1))
+
+ # Начинаем новый чанк с заголовка
+ CHUNK="$HEADER\n\n$COMMIT_WITH_NEWLINE"
+ CURRENT_LENGTH=$((${#HEADER} + 2 + COMMIT_LENGTH))
+ else
+ # Добавляем коммит к текущему чанку
+ CHUNK+="$COMMIT_WITH_NEWLINE"
+ CURRENT_LENGTH=$((CURRENT_LENGTH + COMMIT_LENGTH))
+ fi
+ done
+
+ # Сохраняем последний чанк, если он не пустой
+ if [ "$CHUNK" != "$HEADER\n\n" ]; then
+ printf "%b" "$CHUNK" > "./tmp_messages/part_${PART_INDEX}.txt" || { echo "Error: Failed to write to file" >&2; return 1; }
+ PART_INDEX=$((PART_INDEX + 1))
+ fi
+
+ echo $PART_INDEX
+}
diff --git a/.github/scripts/sh/send_telegram.sh b/.github/scripts/sh/send_telegram.sh
new file mode 100644
index 0000000..ce1dbcd
--- /dev/null
+++ b/.github/scripts/sh/send_telegram.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+# send_telegram.sh
+
+send_telegram_messages() {
+ # Очищаем входные параметры от кавычек
+ local token=$(trim_quotes "$1")
+ local chat_id=$(trim_quotes "$2")
+ local total_parts=$(trim_quotes "$3")
+
+ if [ -z "$token" ] || [ -z "$chat_id" ] || [ -z "$total_parts" ]; then
+ echo "Error: Missing required parameters" >&2
+ echo "Usage: send_telegram_messages token chat_id total_parts" >&2
+ return 1
+ fi
+
+ for i in $(seq 0 $((total_parts - 1))); do
+ if [ ! -f "./tmp_messages/part_${i}.txt" ]; then
+ echo "Error: Message file part_${i}.txt not found" >&2
+ continue
+ fi
+
+ MESSAGE=$(cat "./tmp_messages/part_${i}.txt")
+ echo "Sending part $i to Telegram"
+
+ RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot${token}/sendMessage" \
+ -d "chat_id=${chat_id}" \
+ -d "parse_mode=HTML" \
+ -d "text=${MESSAGE}" \
+ -d "disable_web_page_preview=true")
+
+ if ! echo "$RESPONSE" | grep -q '"ok":true'; then
+ echo "Error sending message part $i: $RESPONSE" >&2
+ fi
+
+ # Добавляем небольшую задержку между отправками сообщений
+ sleep 1
+ done
+}
\ No newline at end of file
diff --git a/.github/scripts/sh/telegram_test.sh b/.github/scripts/sh/telegram_test.sh
new file mode 100755
index 0000000..e8a3c9c
--- /dev/null
+++ b/.github/scripts/sh/telegram_test.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+
+# Функция для отображения справки
+function show_help() {
+ echo "Usage: $0 [OPTIONS]"
+ echo
+ echo "Опции:"
+ echo " -p, --prepare_commits Подготовить коммиты для мержа."
+ echo " -s, --send_telegram Отправить сообщения в Telegram."
+ echo " -h, --help Показать эту справку."
+ echo
+ exit 0
+}
+
+# Переменные для флагов
+prepare=false
+send=false
+
+# Обрабатываем аргументы командной строки
+for arg in "$@"; do
+ case $arg in
+ -h|--help)
+ show_help
+ ;;
+ -p|--prepare_commits)
+ prepare=true
+ ;;
+ -s|--send_telegram)
+ send=true
+ ;;
+ *)
+ echo "Неизвестный аргумент: $arg"
+ show_help
+ ;;
+ esac
+done
+
+if $prepare; then
+ source ./.github/scripts/sh/utils.sh
+ source ./.github/scripts/sh/prepare_commits.sh
+ prepare_commits "repo-name" "main" "13adf7b" "2df69d6" "username" "org/repo"
+fi
+
+if $send; then
+ if [ -z "$TELEGRAM_TOKEN" ] && [ -f .env ]; then
+ export TELEGRAM_TOKEN=$(grep '^TELEGRAM_TOKEN=' .env | awk -F'=' '{print substr($0, index($0,$2))}' | sed 's/^"//; s/"$//')
+ fi
+ if [ -z "$TELEGRAM_TO" ] && [ -f .env ]; then
+ export TELEGRAM_TO=$(grep '^TELEGRAM_TO=' .env | awk -F'=' '{print substr($0, index($0,$2))}' | sed 's/^"//; s/"$//')
+ fi
+ source ./.github/scripts/sh/utils.sh
+ source ./.github/scripts/sh/send_telegram.sh
+ send_telegram_messages $TELEGRAM_TOKEN $TELEGRAM_TO 2
+fi
\ No newline at end of file
diff --git a/.github/scripts/sh/utils.sh b/.github/scripts/sh/utils.sh
new file mode 100644
index 0000000..26b4145
--- /dev/null
+++ b/.github/scripts/sh/utils.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+# utils.sh
+
+# Функция для удаления кавычек из строки
+trim_quotes() {
+ local string="$1"
+ # Удаляем двойные кавычки с начала и конца строки
+ string="${string#\"}"
+ string="${string%\"}"
+ # Удаляем одинарные кавычки с начала и конца строки
+ string="${string#\'}"
+ string="${string%\'}"
+ echo "$string"
+}
diff --git a/.github/workflows/github-telegram.yml b/.github/workflows/github-telegram.yml
index 11c42d5..f02874f 100644
--- a/.github/workflows/github-telegram.yml
+++ b/.github/workflows/github-telegram.yml
@@ -31,7 +31,7 @@ jobs:
# This workflow contains a job called "build" adn "log-github-event-goodies"
push:
- if: ${{ github.event.commits != null }}
+ if: ${{ github.event.commits != null && inputs.additional-text == null }}
# The type of runner that the job will run on
runs-on: ubuntu-latest
@@ -41,65 +41,34 @@ jobs:
- name: Get commits
id: get_commits
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
with:
# checkout full tree
fetch-depth: 0
- - name: Work with commits
- id: with_commits
+ - name: Prepare commit messages
+ id: prepare
run: |
- if [ "${{ github.event.before }}" == "0000000000000000000000000000000000000000" ]; then
- git fetch origin HEAD
- git checkout HEAD
- mapfile -t COMMITS_ARRAY < <(git log --pretty=format:"'%h' - %an, %ar : %s" HEAD..${{ github.sha }})
- echo "before=${{ github.sha }}" >> $GITHUB_OUTPUT
- else
- mapfile -t COMMITS_ARRAY < <(git log --pretty=format:"'%h' - %an, %ar : %s" ${{ github.event.before }}..${{ github.sha }})
- echo "before=${{ github.event.before }}..${{ github.sha }}" >> $GITHUB_OUTPUT
- fi
-
- # Process each commit
- echo "full_list<$additional_text" >> $GITHUB_OUTPUT + echo "" >> $GITHUB_OUTPUT echo "" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT fi diff --git a/.github/workflows/update_cars.yml b/.github/workflows/update_cars.yml new file mode 100644 index 0000000..647b3c3 --- /dev/null +++ b/.github/workflows/update_cars.yml @@ -0,0 +1,84 @@ +name: Generate Astro Files from XML + +on: + # schedule: + # - cron: '0 */4 * * *' # Запускается каждые 4 часа + # push: + # paths: + # - '.github/workflows/github-telegram.yml' + # - 'output.txt' + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + # Указываете окружение и его переменные + environment: + name: ${{ github.ref == 'refs/heads/main' && 'production' || 'development' }} + + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Set output + id: set_output + run: | + if [ -f output.txt ]; then + # Кодируем содержимое файла в base64 + encoded_output=$(base64 -w 0 output.txt) + # Передаем закодированное значение + echo "script_output=$encoded_output" >> $GITHUB_OUTPUT + fi + + - name: cat output + run: | + cat output.txt + + - name: Check for changes + id: check_changes + run: | + if git diff --exit-code; then + echo 'check_changes true — git diff' + echo "changes=true" >> $GITHUB_ENV + echo "changes=true" >> $GITHUB_OUTPUT + elif git status -s; then + echo 'check_changes true — git status' + echo "changes=true" >> $GITHUB_ENV + echo "changes=true" >> $GITHUB_OUTPUT + else + echo 'check_changes else' + echo "false — changes=false" >> $GITHUB_ENV + echo "changes=false" >> $GITHUB_OUTPUT + fi + continue-on-error: true + + - name: Commit files + if: env.changes == 'true' + run: | + git config --local user.email "support+actions@github.com" + git config --local user.name "github-actions-bot" + if [[ -d public/img/thumbs && $(find public/img/thumbs -type f -name "*.webp") ]]; then git add public/img/thumbs/*.webp; fi + if [[ -d src/content/cars && $(find src/content/cars -type f -name "*.mdx") ]]; then git add src/content/cars/*.mdx; fi + if [[ -f public/cars.xml ]]; then git add public/cars.xml; fi + git commit -m "Update cars from XML" -a || echo "No changes to commit" + git remote set-url origin https://git:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git + git push origin $GITHUB_REF_NAME + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + outputs: + changes: ${{ steps.check_changes.outputs.changes }} + script_output: ${{ steps.set_output.outputs.script_output }} + + + notify_telegram: + needs: build + if: ${{ needs.build.outputs.script_output != '' }} + uses: ./.github/workflows/github-telegram.yml + with: + additional-text: | + ${{ needs.build.outputs.script_output }} + secrets: + TELEGRAM_TO: ${{ secrets.TELEGRAM_TO }} + TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }} diff --git a/README.md b/README.md index 13ab18b..7d0b89e 100755 --- a/README.md +++ b/README.md @@ -4,3 +4,28 @@ test repo add -100 to channel id in Telegram + + +```bash +chmod +x ./.github/scripts/sh/test.sh +chmod +x ./.github/scripts/sh/prepare_commits.sh +chmod +x ./.github/scripts/sh/send_telegram.sh + +source ./.github/scripts/sh/utils.sh +source ./.github/scripts/sh/prepare_commits.sh +prepare_commits "repo-name" "main" "13adf7b" "2df69d6" "username" "org/repo" + +source ./.github/scripts/sh/utils.sh +source ./.github/scripts/sh/prepare_commits.sh +prepare_commits "repo-name" "main" "91d47a0" "2df69d6" "username" "org/repo" + +if [ -z "$TELEGRAM_TOKEN" ] && [ -f .env ]; then + export TELEGRAM_TOKEN=$(grep '^TELEGRAM_TOKEN=' .env | awk -F'=' '{print substr($0, index($0,$2))}' | sed 's/^"//; s/"$//') +fi +if [ -z "$TELEGRAM_TO" ] && [ -f .env ]; then + export TELEGRAM_TO=$(grep '^TELEGRAM_TO=' .env | awk -F'=' '{print substr($0, index($0,$2))}' | sed 's/^"//; s/"$//') +fi +source ./.github/scripts/sh/utils.sh +source ./.github/scripts/sh/send_telegram.sh +send_telegram_messages $TELEGRAM_TOKEN $TELEGRAM_TO 2 +``` diff --git a/index.html b/index.html index f3d662a..b27f686 100644 --- a/index.html +++ b/index.html @@ -2,9 +2,11 @@
I'm hosted with GitHub Pages.
+1
2
3
+3
+ - \ No newline at end of file +