diff --git a/.github/scripts/sh/prepare_commits.sh b/.github/scripts/sh/prepare_commits.sh new file mode 100755 index 0000000..c1665ae --- /dev/null +++ b/.github/scripts/sh/prepare_commits.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# prepare_commits.sh + +prepare_commits() { + # Очищаем входные параметры от кавычек + local repository_name=$(trim_quotes "$1") + local ref_name=$(trim_quotes "$2") + local before_sha=$(trim_quotes "$3") + local after_sha=$(trim_quotes "$4") + local actor=$(trim_quotes "$5") + local repository=$(trim_quotes "$6") + + # Проверка наличия всех параметров + if [ -z "$repository_name" ] || [ -z "$ref_name" ] || [ -z "$before_sha" ] || [ -z "$after_sha" ] || [ -z "$actor" ] || [ -z "$repository" ]; then + echo "Error: Missing required parameters" >&2 + echo "Usage: prepare_commits repository_name ref_name before_sha after_sha actor repository" >&2 + return 1 + fi + + # Максимальная длина сообщения в Telegram + local MAX_LENGTH=4096 + # Длина для эллипсиса и дополнительного пробела + local ELLIPSIS_LENGTH=4 + + # Инициализируем массив + declare -a readarray + + if [ "$before_sha" = "0000000000000000000000000000000000000000" ]; then + git fetch origin HEAD || { echo "Error: Failed to fetch git repository" >&2; return 1; } + git checkout HEAD || { echo "Error: Failed to checkout HEAD" >&2; return 1; } + + # Читаем вывод git log в массив + mapfile -t readarray < <(git log --pretty=format:"%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<> $GITHUB_OUTPUT - for COMMIT in "${COMMITS_ARRAY[@]}"; do - echo "$COMMIT" >> $GITHUB_OUTPUT - done - echo "EOF" >> $GITHUB_OUTPUT - - LINES_COUNT=${#COMMITS_ARRAY[*]} - if [ "$LINES_COUNT" == "1" ]; then - echo "lines_count=$LINES_COUNT new commit" >> $GITHUB_OUTPUT - else - echo "lines_count=$LINES_COUNT new commits" >> $GITHUB_OUTPUT - fi - - - - name: Set outputs - id: set_outputs - # The part of this solution to focus on is that we’re substituting the %, \n, and \r characters + source ./.github/scripts/sh/utils.sh + source ./.github/scripts/sh/prepare_commits.sh + total_parts=$(prepare_commits \ + "${{ github.event.repository.name }}" \ + "${{ github.ref_name }}" \ + "${{ github.event.before }}" \ + "${{ github.sha }}" \ + "${{ github.actor }}" \ + "${{ github.repository }}") + echo "total_parts=${total_parts}" >> $GITHUB_OUTPUT + + - name: Send messages to Telegram + if: ${{ steps.prepare.outputs.total_parts != '0' }} run: | - additional_text="${{ inputs.additional-text || '' }}" - if [ "$additional_text" != "" ]; then - echo "additional_text<> $GITHUB_OUTPUT - echo "" >> $GITHUB_OUTPUT - echo $additional_text >> $GITHUB_OUTPUT - echo "" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT - fi - - - name: Send message to Telegram - if: ${{ steps.with_commits.outputs.full_list != '' }} - uses: appleboy/telegram-action@master - with: - to: ${{ secrets.TELEGRAM_TO }} - token: ${{ secrets.TELEGRAM_TOKEN }} - disable_web_page_preview: true - format: html - message: | - [${{ github.event.repository.name }}:${{ github.ref_name }}] ${{ steps.with_commits.outputs.lines_count }} by ${{ github.actor }} - ${{ steps.set_outputs.outputs.additional_text }} - ${{ steps.with_commits.outputs.full_list }} - + source ./.github/scripts/sh/utils.sh + source ./.github/scripts/sh/send_telegram.sh + send_telegram_messages \ + "${{ secrets.TELEGRAM_TOKEN }}" \ + "${{ secrets.TELEGRAM_TO }}" \ + "${{ steps.prepare.outputs.total_parts }}" create: @@ -173,7 +142,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Update repository run: git pull @@ -192,11 +161,19 @@ jobs: id: set_outputs # The part of this solution to focus on is that we’re substituting the %, \n, and \r characters run: | - additional_text="${{ inputs.additional-text || '' }}" + additional_text=$(echo "${{ inputs.additional-text || '' }}" | base64 -d) if [ "$additional_text" != "" ]; then + # Форматируем текст с переносами строк + additional_text=$(echo -e "$additional_text") + + # Debug: print the formatted text + echo "Formatted additional_text:" + echo "$additional_text" + echo "additional_text<> $GITHUB_OUTPUT echo "" >> $GITHUB_OUTPUT - echo $additional_text >> $GITHUB_OUTPUT + echo "
$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 @@

Hello World

-

I'm hosted with GitHub Pages.

+

ссылка

1

2

3

+

3

+

ссылка

- \ No newline at end of file + diff --git a/output.txt b/output.txt new file mode 100644 index 0000000..91f74ea --- /dev/null +++ b/output.txt @@ -0,0 +1 @@ +Error: Model 'Emgrand, II' or Color 'Серый' not found\nError: Model 'Emgrand, II' or Color 'Желтый' not found\nError: Model 'Emgrand, II' or Color 'Желтый' not found\n \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e6ed465 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "alexsab.github.io", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e7bc882 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "alexsab.github.io", + "version": "1.0.0", + "description": "[github pages](https://alexsab.github.io)", + "main": "index.js", + "scripts": { + "prepare_commits": "./.github/scripts/sh/telegram_test.sh --prepare_commits", + "send_telegram": "./.github/scripts/sh/telegram_test.sh --send_telegram" + }, + "author": "Alexsab.ru", + "license": "ISC" +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..2b9f188 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,5 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false