diff --git a/.gitea/workflows/build.yaml b/.gitea/workflows/build.yaml index 2917fa4..8572518 100644 --- a/.gitea/workflows/build.yaml +++ b/.gitea/workflows/build.yaml @@ -1,27 +1,82 @@ -name: Release Build +name: Conditional Release Build on: push: tags: - v* jobs: - create-release: + read-conditions: runs-on: ubuntu-latest - container: - # image: golang:1.21 - # image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:builder-1.0.32 - image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:latest + outputs: + create-release: ${{ steps.parse-conditions.outputs.create-release }} + create-docker-image: ${{ steps.parse-conditions.outputs.create-docker-image }} + update-to-release-branch: ${{ steps.parse-conditions.outputs.update-to-release-branch }} steps: - name: Checkout repository run: | git clone https://oauth2:${{ secrets.GITEATOKEN }}@direct-dev.ru/gitea/GiteaAdmin/hello_gitea.git hello_gitea cd hello_gitea - git checkout ${{ github.ref }} + git checkout ${{ github.ref }} + + - name: Parse build conditions + id: parse-conditions + run: | + cd hello_gitea + + # Default values if file doesn't exist + CREATE_RELEASE="1" + CREATE_DOCKER_IMAGE="1" + UPDATE_TO_RELEASE_BRANCH="1" + + # Read conditions from file if it exists + if [ -f .build.conditions ]; then + echo "Reading .build.conditions file..." + while IFS=':' read -r job condition; do + # Remove leading/trailing whitespace + job=$(echo "$job" | xargs) + condition=$(echo "$condition" | xargs) + + case "$job" in + "create-release") + CREATE_RELEASE="$condition" + ;; + "create-docker-image") + CREATE_DOCKER_IMAGE="$condition" + ;; + "update-to-release-branch") + UPDATE_TO_RELEASE_BRANCH="$condition" + ;; + esac + done < .build.conditions + + echo "Parsed conditions:" + echo " create-release: $CREATE_RELEASE" + echo " create-docker-image: $CREATE_DOCKER_IMAGE" + echo " update-to-release-branch: $UPDATE_TO_RELEASE_BRANCH" + else + echo "No .build.conditions file found, using defaults" + fi + + # Set outputs + echo "create-release=$CREATE_RELEASE" >> $GITHUB_OUTPUT + echo "create-docker-image=$CREATE_DOCKER_IMAGE" >> $GITHUB_OUTPUT + echo "update-to-release-branch=$UPDATE_TO_RELEASE_BRANCH" >> $GITHUB_OUTPUT + + create-release: + runs-on: ubuntu-latest + needs: read-conditions + if: needs.read-conditions.outputs.create-release == '1' + container: + image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:latest + steps: + - name: Checkout repository + run: | + git clone https://oauth2:${{ secrets.GITEATOKEN }}@direct-dev.ru/gitea/GiteaAdmin/hello_gitea.git hello_gitea + cd hello_gitea + git checkout ${{ github.ref }} - name: Setup Go run: | - # Install jq for JSON parsing - # apt-get update && apt-get install -y jq git --version go version jq --version @@ -29,6 +84,13 @@ jobs: - name: Build all binaries run: | cd hello_gitea + + # Проверяем, изменились ли зависимости + if [ ! -f go.sum ] || ! go mod verify >/dev/null 2>&1; then + echo "Dependencies changed, downloading..." + go mod download + fi + mkdir -p bin echo "Building for all platforms..." @@ -99,13 +161,13 @@ jobs: create-docker-image: runs-on: ubuntu-latest + needs: [read-conditions, create-release] + if: needs.read-conditions.outputs.create-docker-image == '1' && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped') container: image: docker:28.3.2-dind - needs: create-release steps: - name: Checkout repository run: | - # Install git apk add --no-cache git echo "=== GitHub Variables ===" @@ -151,49 +213,26 @@ jobs: update-to-release-branch: runs-on: ubuntu-latest + needs: [read-conditions, create-docker-image] + if: needs.read-conditions.outputs.update-to-release-branch == '1' && (needs.create-docker-image.result == 'success' || needs.create-docker-image.result == 'skipped') container: image: docker:28.3.2-dind - needs: create-docker-image steps: - name: Create Release Branch run: | - echo "Creating release branch..." - echo "=== GitHub Variables ===" - echo "github.ref = ${{ github.ref }}" - echo "github.ref_name = ${{ github.ref_name }}" - echo "github.sha = ${{ github.sha }}" - echo "github.repository = ${{ github.repository }}" - echo "DOCKERHUB_USERNAME = ${{ secrets.DOCKERHUB_USERNAME }}" - echo "DOCKERHUB_TOKEN = ${{ secrets.DOCKERHUB_TOKEN }}" - echo "GITEATOKEN = ${{ secrets.GITEATOKEN }}" - echo "========================" - # Clone repository - echo "Cloning repository..." + apk add --no-cache git git clone https://oauth2:${{ secrets.GITEATOKEN }}@direct-dev.ru/gitea/GiteaAdmin/hello_gitea.git hello_gitea cd hello_gitea - # Configure git - echo "Configuring git..." git config user.email "info@direct-dev.ru" git config user.name "Direct-Dev-Robot" - # Check if release branch exists - echo "Checking if release branch exists..." if git ls-remote --heads origin release | grep -q release; then - echo "Release branch exists, checking out..." git checkout release - echo "release branch exists - pulling release branch..." git pull origin release else - echo "release branch does not exist - creating new release branch..." git checkout -b release fi - # Reset to the tag commit - echo "Resetting to the tag commit ${{ github.ref_name }} ..." git reset --hard ${{ github.ref_name }} - - # Push changes to release branch - echo "Pushing changes to release branch..." - git push origin release --force - echo "Changes pushed to release branch successfully" \ No newline at end of file + git push origin release --force \ No newline at end of file diff --git a/Dockerfile.builder b/Dockerfile.builder index 8964866..e08892d 100644 --- a/Dockerfile.builder +++ b/Dockerfile.builder @@ -18,12 +18,6 @@ COPY go.mod go.sum ./ # Предварительно загружаем все зависимости RUN go mod download && go mod verify -# Создаем скрипт для быстрой сборки -COPY scripts/quick-build.sh /usr/local/bin/quick-build - -# делаем скрипт исполняемым -RUN chmod +x /usr/local/bin/quick-build - # Устанавливаем переменные окружения ENV GOPATH=/go ENV PATH=$PATH:/go/bin:/usr/local/bin diff --git a/docs/gitea-actions-guide.md b/docs/gitea-actions-guide.md index 034d6fb..a1902c9 100644 --- a/docs/gitea-actions-guide.md +++ b/docs/gitea-actions-guide.md @@ -1,6 +1,7 @@ # Настройка Gitea Actions для Go проекта: Полное руководство ```metadata +id: 4 readTime: 15-20 минут date: 2025-07-27 18:00 author: Direct-Dev(aka Антон Кузнецов) @@ -27,7 +28,7 @@ C. [Настройка Gitea Runner в LXC контейнере](#настрой Gitea Actions — это встроенная система непрерывной интеграции и развертывания (CI/CD) в Gitea, которая позволяет автоматизировать процессы сборки, тестирования и развертывания ваших проектов. Большой плюс этой системы в том, что она достаточна не требовательна к ресурсам и может быть развернута в собственном изолированном окружении. -В этой статье мы рассмотрим пример работы с данной системой, на примере того как настроить Gitea Actions для Go проекта с автоматической сборкой мультиплатформенных бинарников, созданием Docker образов и публикацией релизов. +В этой статье мы рассмотрим как работать с данной системой, на примере настройки Gitea Actions для Go проекта с автоматической сборкой мультиплатформенных бинарников, созданием Docker образов и публикацией релизов. ### Итак, что мы будем делать @@ -35,6 +36,7 @@ Gitea Actions — это встроенная система непрерывн - Создадим Docker образы для Linux AMD64 и ARM64 - Настроим публикацию в Docker Hub - Автоматизируем создание релизов с бинарниками +- Сделаем коммит в отдельную ветку - которую можно связать с CD системой (flux/ArgoCD) - Настроим триггеры на основе Git тегов ## Подготовка проекта @@ -45,15 +47,18 @@ Gitea Actions — это встроенная система непрерывн ``` text hello_gitea/ -├── main.go # Основной код приложения -├── go.mod # Зависимости Go -├── go.sum # Хеши зависимостей -├── Dockerfile # Docker образ -├── .gitea/ # Конфигурация Gitea Actions +├── .gitea/ # Конфигурация Gitea Actions └── workflows/ - └── build.yaml # Workflow для сборки -├── README.md # Документация -└── .gitignore # Исключения Git + └── build.yaml # Workflow для сборки +├── main.go # Основной код приложения +├── go.mod # Зависимости Go +├── go.sum # Хеши зависимостей +├── Dockerfile # Docker образ +├── Dockerfile.builder # Docker образ для образа-билдера проекта +├── scripts/ # Вспомогательные скрипты + └── release-interactive.sh # Скрипт для пушинга релиза +├── README.md # Документация +└── .gitignore # Исключения Git ``` ### Анализ кода @@ -245,13 +250,14 @@ jobs: runs-on: ubuntu-latest container: # image: golang:1.21 - image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:latest + # image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:builder-1.0.32 + image: ${{ secrets.DOCKERHUB_USERNAME }}/my-build-golang-runner:latest steps: - name: Checkout repository run: | git clone https://oauth2:${{ secrets.GITEATOKEN }}@direct-dev.ru/gitea/GiteaAdmin/hello_gitea.git hello_gitea cd hello_gitea - git checkout ${{ github.ref }} + git checkout ${{ github.ref }} - name: Setup Go run: | @@ -264,29 +270,51 @@ jobs: - name: Build all binaries run: | cd hello_gitea - mkdir -p bin - # Build for all platforms + # Проверяем, изменились ли зависимости + if [ ! -f go.sum ] || ! go mod verify >/dev/null 2>&1; then + echo "Dependencies changed, downloading..." + go mod download + fi + + mkdir -p bin + echo "Building for all platforms..." + + # Build for all platforms using direct go build commands + echo "Building for linux amd64..." GOOS=linux GOARCH=amd64 go build -o bin/hello-api-linux-amd64 main.go + + echo "Building for linux arm64..." GOOS=linux GOARCH=arm64 go build -o bin/hello-api-linux-arm64 main.go + + echo "Building for windows amd64..." GOOS=windows GOARCH=amd64 go build -o bin/hello-api-windows-amd64.exe main.go + + echo "Building for darwin amd64..." GOOS=darwin GOARCH=amd64 go build -o bin/hello-api-darwin-amd64 main.go + + echo "Building for darwin arm64..." GOOS=darwin GOARCH=arm64 go build -o bin/hello-api-darwin-arm64 main.go # Create archives + echo "Creating archives..." cd bin + + # Create archives with correct file names tar -czf hello-api-linux-amd64.tar.gz hello-api-linux-amd64 tar -czf hello-api-linux-arm64.tar.gz hello-api-linux-arm64 tar -czf hello-api-windows-amd64.tar.gz hello-api-windows-amd64.exe tar -czf hello-api-darwin-amd64.tar.gz hello-api-darwin-amd64 tar -czf hello-api-darwin-arm64.tar.gz hello-api-darwin-arm64 - + + echo "Listing bin directory..." ls -la - name: Create Release run: | cd hello_gitea # Create release using Gitea API + echo "Creating release..." curl -X POST \ -H "Authorization: token ${{ secrets.GITEATOKEN }}" \ -H "Content-Type: application/json" \ @@ -299,12 +327,13 @@ jobs: }' \ "https://direct-dev.ru/gitea/api/v1/repos/GiteaAdmin/hello_gitea/releases" - # Upload assets + echo "Getting release id..." RELEASE_ID=$(curl -s -H "Authorization: token ${{ secrets.GITEATOKEN }}" \ "https://direct-dev.ru/gitea/api/v1/repos/GiteaAdmin/hello_gitea/releases/tags/${{ github.ref_name }}" | \ jq -r '.id') # Upload all binaries + echo "Uploading assets..." for file in bin/*.tar.gz; do echo "Uploading $file..." curl -X POST \ @@ -314,6 +343,8 @@ jobs: "https://direct-dev.ru/gitea/api/v1/repos/GiteaAdmin/hello_gitea/releases/$RELEASE_ID/assets?name=$(basename $file)" done + echo "Release created successfully" + create-docker-image: runs-on: ubuntu-latest container: @@ -339,9 +370,9 @@ jobs: run: | # Docker is already installed in docker:dind image docker --version - + echo "Setting up Docker Buildx for multi-platform builds..." # Setup Docker Buildx for multi-platform builds - docker buildx create --use + docker buildx create --name go-buildx --use docker buildx inspect --bootstrap - name: Login to Docker Hub @@ -351,6 +382,7 @@ jobs: - name: Build multi-platform Docker images run: | cd hello_gitea + echo "Building multi-platform images using buildx..." # Build multi-platform images using buildx docker buildx build \ --platform linux/amd64,linux/arm64 \ @@ -358,6 +390,12 @@ jobs: --tag ${{ secrets.DOCKERHUB_USERNAME }}/hello-api:latest \ --push \ . + echo "Multi-platform images built successfully" + + - name: Remove buildx + run: | + echo "Removing buildx..." + docker buildx rm go-buildx update-to-release-branch: runs-on: ubuntu-latest @@ -367,6 +405,7 @@ jobs: steps: - name: Create Release Branch run: | + echo "Creating release branch..." echo "=== GitHub Variables ===" echo "github.ref = ${{ github.ref }}" echo "github.ref_name = ${{ github.ref_name }}" @@ -405,6 +444,7 @@ jobs: # Push changes to release branch echo "Pushing changes to release branch..." git push origin release --force + echo "Changes pushed to release branch successfully" ``` ### Разберемся как работает workflow @@ -450,6 +490,19 @@ RUN apt-get update && \ jq && \ rm -rf /var/lib/apt/lists/* +# Создаем рабочую директорию +WORKDIR /app + +# Копируем файлы зависимостей +COPY go.mod go.sum ./ + +# Предварительно загружаем все зависимости +RUN go mod download && go mod verify + +# Устанавливаем переменные окружения +ENV GOPATH=/go +ENV PATH=$PATH:/go/bin:/usr/local/bin + # (Опционально) Можно добавить команду по умолчанию CMD ["bash"] ``` @@ -467,7 +520,7 @@ docker buildx build \ . ``` -решение рабочее но надо всегда иметь под рукой АРм с buildx или лучше автоматизировать все и сделать задачу для сборки на раннере `.gitea/workflows/build-builder.yaml` +решение рабочее, но надо всегда иметь под рукой комп с buildx - лучше автоматизировать все и сделать задачу для сборки на раннере `.gitea/workflows/build-builder.yaml` ```yaml name: Build Builder Docker Image diff --git a/main.go b/main.go index f1c955e..82b44bc 100644 --- a/main.go +++ b/main.go @@ -11,7 +11,7 @@ import ( "github.com/gin-gonic/gin" ) -const version = "1.0.40" +const version = "1.0.50" // SystemInfo holds system information type SystemInfo struct { diff --git a/makefile b/makefile index cb321c0..758dc50 100644 --- a/makefile +++ b/makefile @@ -2,7 +2,7 @@ BIN_DIR=bin APP_NAME=hello-api -VERSION=1.0.40 +VERSION=1.0.50 build: mkdir -p $(BIN_DIR)