ci: daily upstream merge with PR/issue, tag-based image publishing
- scripts/upstream-sync.sh + upstream-sync-check.yml: fast-forward upstream-sync, merge upstream into maintenance/sync-upstream-<sha> from maintained-develop, build/vet/test, open PR (or Issue on conflict), warn on newer whatsmeow. Optional AUTO_MERGE_UPSTREAM repo variable; maintained-stable never touched. - docker-build.yml: publish git.jf.eng.br/jfeng/evogo:<version> and <version>-<sha7> on tag v*, startup smoke test, non-blocking Trivy scan, :latest only on explicit promote_latest. - CHANGELOG and maintenance docs updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
e02441fc4e
commit
2453ed2be8
6 files changed
+417
-63
No files matched your search
@@ -1,11 +1,19 @@
|
|||||||
name: Docker - Build e Publicacao
|
name: Docker - Build e Publicacao
|
||||||
|
|
||||||
|
# Publicacao no registry do Gitea (git.jf.eng.br/jfeng/evogo):
|
||||||
|
# - push de tag v<versao> (ex: v0.7.2-evogo.1) = release aprovado -> publica
|
||||||
|
# git.jf.eng.br/jfeng/evogo:<versao> (tag semantica)
|
||||||
|
# git.jf.eng.br/jfeng/evogo:<versao>-<sha7> (tag imutavel do commit)
|
||||||
|
# - workflow_dispatch com publish_image=true -> idem, versao = target_tag ou VERSION
|
||||||
|
# - push em maintained-stable -> apenas build + teste + scan (nao publica)
|
||||||
|
# :latest so e atualizada com promote_latest=true (manual), nunca automaticamente.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- maintained-stable
|
- maintained-stable
|
||||||
tags:
|
tags:
|
||||||
- 'v*.*.*'
|
- 'v*'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
publish_image:
|
publish_image:
|
||||||
@@ -14,14 +22,23 @@ on:
|
|||||||
default: false
|
default: false
|
||||||
required: true
|
required: true
|
||||||
target_tag:
|
target_tag:
|
||||||
description: 'Tag semantica para publicacao (ex: 0.7.2)'
|
description: 'Tag semantica para publicacao (ex: 0.7.2-evogo.1). Vazio = arquivo VERSION'
|
||||||
type: string
|
type: string
|
||||||
default: ''
|
default: ''
|
||||||
required: false
|
required: false
|
||||||
|
promote_latest:
|
||||||
|
description: 'Tambem atualizar :latest (somente versoes aprovadas em maintained-stable)'
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
required: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: git.jf.eng.br
|
||||||
|
IMAGE: git.jf.eng.br/jfeng/evogo
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build_docker:
|
build_docker:
|
||||||
name: Build e Verificacao Docker
|
name: Build, Scan e Publicacao
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
@@ -31,44 +48,72 @@ jobs:
|
|||||||
- name: Obter Versao e Commit SHA
|
- name: Obter Versao e Commit SHA
|
||||||
id: meta
|
id: meta
|
||||||
run: |
|
run: |
|
||||||
VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
|
||||||
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
COMMIT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||||
echo "commit_sha=${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
VERSION="${{ github.ref_name }}"
|
||||||
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> $GITHUB_OUTPUT
|
VERSION="${VERSION#v}"
|
||||||
|
PUBLISH=true
|
||||||
- name: Configurar Docker Buildx
|
else
|
||||||
uses: docker/setup-buildx-action@v3
|
VERSION="${{ github.event.inputs.target_tag }}"
|
||||||
|
[ -n "$VERSION" ] || VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
|
||||||
|
PUBLISH="${{ github.event.inputs.publish_image == 'true' }}"
|
||||||
|
fi
|
||||||
|
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "commit_sha=${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "image_tag=${VERSION}-${COMMIT_SHA}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "publish=${PUBLISH}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Versao: ${VERSION} | Commit: ${COMMIT_SHA} | Publicar: ${PUBLISH}"
|
||||||
|
|
||||||
- name: Construir Imagem Docker Local
|
- name: Construir Imagem Docker Local
|
||||||
uses: docker/build-push-action@v5
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
load: true
|
|
||||||
tags: evogo:local
|
|
||||||
build-args: |
|
|
||||||
VERSION=${{ steps.meta.outputs.image_tag }}
|
|
||||||
|
|
||||||
- name: Testar Execucao Basica do Container
|
|
||||||
run: |
|
run: |
|
||||||
docker run --rm evogo:local --help || echo "Container executou verificacao inicial com sucesso"
|
docker build \
|
||||||
|
--build-arg VERSION=${{ steps.meta.outputs.image_tag }} \
|
||||||
|
-t evogo:ci-${{ steps.meta.outputs.commit_sha }} .
|
||||||
|
|
||||||
- name: Login no Gitea Package Registry (se aprovado)
|
- name: Testar Inicializacao do Container
|
||||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
run: |
|
||||||
uses: docker/login-action@v3
|
# O binario precisa subir e falhar apenas por falta de banco/config,
|
||||||
with:
|
# nunca por erro de link (CGO/libwebp/libjpeg) ou arquivo ausente.
|
||||||
registry: git.jf.eng.br
|
set +e
|
||||||
username: ${{ secrets.REGISTRY_USER || github.actor }}
|
timeout 20 docker run --rm evogo:ci-${{ steps.meta.outputs.commit_sha }} > /tmp/run.log 2>&1
|
||||||
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}
|
set -e
|
||||||
|
tail -20 /tmp/run.log
|
||||||
|
if grep -qiE "error while loading shared libraries|exec format error|exec /app/server" /tmp/run.log; then
|
||||||
|
echo "Falha ao iniciar o binario dentro da imagem"; exit 1
|
||||||
|
fi
|
||||||
|
docker run --rm --entrypoint sh evogo:ci-${{ steps.meta.outputs.commit_sha }} -c 'test -x /app/server && test -d /app/manager/dist && cat /app/VERSION'
|
||||||
|
|
||||||
- name: Publicar Imagens no Registry (apenas com aprovacao expressa)
|
- name: Verificar Vulnerabilidades (Trivy, nao bloqueante)
|
||||||
if: ${{ github.event.inputs.publish_image == 'true' || github.event.inputs.publish_image == true }}
|
continue-on-error: true
|
||||||
uses: docker/build-push-action@v5
|
run: |
|
||||||
with:
|
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
|
||||||
context: .
|
image --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
|
||||||
push: true
|
evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||||
tags: |
|
|
||||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.image_tag }}
|
- name: Login no Gitea Package Registry
|
||||||
git.jf.eng.br/jfeng/evogo:${{ steps.meta.outputs.version }}
|
if: steps.meta.outputs.publish == 'true'
|
||||||
build-args: |
|
run: |
|
||||||
VERSION=${{ steps.meta.outputs.image_tag }}
|
USER="${{ secrets.REGISTRY_USER }}"
|
||||||
|
[ -n "$USER" ] || USER="${{ github.actor }}"
|
||||||
|
TOKEN="${{ secrets.REGISTRY_TOKEN }}"
|
||||||
|
[ -n "$TOKEN" ] || TOKEN="${{ secrets.GITEA_TOKEN }}"
|
||||||
|
echo "$TOKEN" | docker login "$REGISTRY" -u "$USER" --password-stdin
|
||||||
|
|
||||||
|
- name: Publicar Imagens no Registry
|
||||||
|
if: steps.meta.outputs.publish == 'true'
|
||||||
|
run: |
|
||||||
|
SRC=evogo:ci-${{ steps.meta.outputs.commit_sha }}
|
||||||
|
for TAG in "${{ steps.meta.outputs.image_tag }}" "${{ steps.meta.outputs.version }}"; do
|
||||||
|
docker tag "$SRC" "$IMAGE:$TAG"
|
||||||
|
docker push "$IMAGE:$TAG"
|
||||||
|
echo "Publicado: $IMAGE:$TAG"
|
||||||
|
done
|
||||||
|
if [ "${{ github.event.inputs.promote_latest }}" = "true" ]; then
|
||||||
|
docker tag "$SRC" "$IMAGE:latest"
|
||||||
|
docker push "$IMAGE:latest"
|
||||||
|
echo "Publicado: $IMAGE:latest"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Limpeza
|
||||||
|
if: always()
|
||||||
|
run: docker image rm -f evogo:ci-${{ steps.meta.outputs.commit_sha }} >/dev/null 2>&1 || true
|
||||||
@@ -1,29 +1,53 @@
|
|||||||
name: Monitoramento Diario do Upstream
|
name: Sincronizacao Diaria com o Upstream
|
||||||
|
|
||||||
|
# Incorpora o upstream oficial (evolution-foundation/evolution-go) sem perder as
|
||||||
|
# correcoes EvoGO: o merge e feito numa branch maintenance/sync-upstream-<sha>
|
||||||
|
# criada a partir de maintained-develop, testado e enviado como PR.
|
||||||
|
# Conflitos viram Issue. maintained-stable nunca e tocada.
|
||||||
|
# Ver scripts/upstream-sync.sh e docs/maintenance/UPSTREAM_SYNC.md.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
# Executa diariamente as 04:00 UTC (01:00 BRT)
|
# Diariamente as 04:00 UTC (01:00 BRT)
|
||||||
- cron: '0 4 * * *'
|
- cron: '0 4 * * *'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: upstream-sync
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check_upstream:
|
sync:
|
||||||
name: Verificar Atualizacoes do Upstream e Whatsmeow
|
name: Incorporar upstream e verificar whatsmeow
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout do Repositorio
|
- name: Checkout do Repositorio
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
|
ref: maintained-develop
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
token: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
|
||||||
- name: Executar Script de Verificacao
|
- name: Configurar Go
|
||||||
id: check
|
uses: actions/setup-go@v5
|
||||||
run: |
|
|
||||||
bash scripts/check-upstream-updates.sh
|
|
||||||
|
|
||||||
- name: Salvar Relatorio como Artefato
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
with:
|
||||||
name: relatorio-upstream-${{ github.run_id }}
|
go-version-file: go.mod
|
||||||
path: relatorio_atualizacao_*.md
|
|
||||||
|
- name: Instalar Dependencias de Sistema
|
||||||
|
run: |
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y -qq --no-install-recommends libjpeg-dev libwebp-dev
|
||||||
|
|
||||||
|
- name: Sincronizar com o upstream
|
||||||
|
env:
|
||||||
|
GITEA_URL: ${{ github.server_url }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
# Defina a variavel de repositorio AUTO_MERGE_UPSTREAM=true para mesclar
|
||||||
|
# automaticamente em maintained-develop quando build e testes passarem.
|
||||||
|
AUTO_MERGE: ${{ vars.AUTO_MERGE_UPSTREAM || 'false' }}
|
||||||
|
run: |
|
||||||
|
git config user.name "EvoGO Upstream Bot"
|
||||||
|
git config user.email "[email protected]"
|
||||||
|
bash scripts/upstream-sync.sh
|
||||||
@@ -18,6 +18,36 @@
|
|||||||
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
|
- **Migração automática do banco de autenticação** — o schema do whatsmeow sobe
|
||||||
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
|
de v14 para v16 (`companion_meta_nonce`, `wasa_root_secret_id`). Roda sozinho
|
||||||
ao abrir o container; testado com banco SQLite v14 existente.
|
ao abrir o container; testado com banco SQLite v14 existente.
|
||||||
|
- **Build quebrado após o fix 405** — `whatsmeow.go` referenciava `waProto`
|
||||||
|
(pacote inexistente); `ClientPayload_UserAgent_AppVersion` vem de
|
||||||
|
`go.mau.fi/whatsmeow/proto/waWa6`.
|
||||||
|
|
||||||
|
### 🛡️ Estabilidade (correções da comunidade incorporadas pelo EvoGO)
|
||||||
|
- **Crash `concurrent map writes`** — `clientPointer`, `myClientPointer` e
|
||||||
|
`killChannel` agora são `safemap.Map` com RWMutex (upstream PR #196, issue #203).
|
||||||
|
- **Vazamento de conexões Postgres** — um único `sqlstore.Container`
|
||||||
|
compartilhado em vez de um novo pool a cada `StartClient`/reconexão
|
||||||
|
(upstream PR #206, issues #165/#175/#215).
|
||||||
|
- **Loop de reconexão/QR infinito** — backoff progressivo após 5 reinícios em
|
||||||
|
15 min (upstream PR #197); cliente sem dispositivo pareado não é reiniciado
|
||||||
|
(upstream PR #240); `StartClient` duplicado é ignorado (upstream PR #239).
|
||||||
|
- **Panics que derrubavam todas as instâncias** — `ReconnectClient` serializado
|
||||||
|
por instância com checagem de nil (issue #188); envio em canal fechado ao
|
||||||
|
excluir instância durante o QR (issue #222); evento `Archive` (upstream PR #195).
|
||||||
|
- **Webhooks paravam após desconectar pela API** — `Disconnect` não apaga mais
|
||||||
|
as inscrições de eventos (upstream PR #187).
|
||||||
|
- **`/user/info` e `/user/avatar` travando 75 s** — `ParseJID` remove o `+` de
|
||||||
|
JIDs de usuário (upstream PR #224, issue #223).
|
||||||
|
- **WebSocket** — todos os assinantes de uma instância recebem eventos e as
|
||||||
|
escritas são serializadas por conexão (upstream PR #181).
|
||||||
|
- **NATS** — sem `NATS_URL` a conexão não é tentada (upstream PR #143).
|
||||||
|
|
||||||
|
### ⚙️ Manutenção EvoGO
|
||||||
|
- Sincronização diária com o upstream via Gitea Actions: merge em
|
||||||
|
`maintenance/sync-upstream-<sha>` a partir de `maintained-develop`, build/testes
|
||||||
|
e PR automático; conflitos viram Issue; aviso de whatsmeow desatualizado.
|
||||||
|
- Publicação da imagem em `git.jf.eng.br/jfeng/evogo` por tag `v*`, com tag
|
||||||
|
imutável `<versão>-<sha7>` e scan Trivy.
|
||||||
|
|
||||||
## v0.7.2
|
## v0.7.2
|
||||||
|
|
||||||
|
|||||||
@@ -82,11 +82,32 @@ docker build \
|
|||||||
|
|
||||||
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
O pipeline é orquestrado via `.gitea/workflows/docker-build.yml`:
|
||||||
|
|
||||||
1. **Trigger em Pull Requests ou Push em develop:**
|
1. **Push em `maintained-stable`:** build da imagem (`linux/amd64`), teste de
|
||||||
- Executa `go vet` e `go test`.
|
inicialização do binário e scan Trivy (HIGH/CRITICAL, não bloqueante).
|
||||||
- Executa `docker build` para garantir que a imagem compila sem erros.
|
**Não publica.**
|
||||||
- **Não faz push** para o registry.
|
2. **Push de tag `v<versão>` (release aprovado):** mesmo build/teste/scan e
|
||||||
2. **Trigger em Tag ou Push em `maintained-stable`:**
|
publicação de:
|
||||||
- Constrói a imagem multiplataforma (`linux/amd64`, `linux/arm64`).
|
- `git.jf.eng.br/jfeng/evogo:<versão>-<sha7>` (imutável)
|
||||||
- Gera tag imutável associada ao commit.
|
- `git.jf.eng.br/jfeng/evogo:<versão>`
|
||||||
- Requer aprovação ou execução via `workflow_dispatch` para publicação em produção.
|
3. **`workflow_dispatch`:** publica apenas com `publish_image=true`; `:latest`
|
||||||
|
só com `promote_latest=true`.
|
||||||
|
|
||||||
|
### Gerar um release
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout maintained-develop && git pull
|
||||||
|
git tag -a v0.7.2-evogo.1 -m "EvoGO 0.7.2-evogo.1"
|
||||||
|
git push origin v0.7.2-evogo.1 # dispara o build e a publicação
|
||||||
|
```
|
||||||
|
|
||||||
|
### Usar no docker-compose
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
evolution-go:
|
||||||
|
image: git.jf.eng.br/jfeng/evogo:0.7.2-evogo.1
|
||||||
|
```
|
||||||
|
|
||||||
|
Como o pacote é privado, o host precisa de `docker login git.jf.eng.br`
|
||||||
|
(usuário Gitea + token com escopo `read:package`) antes de `docker compose pull`.
|
||||||
|
Para fixar exatamente o commit testado, use a tag imutável `<versão>-<sha7>`.
|
||||||
@@ -26,7 +26,33 @@ git remote add upstream https://github.com/evolution-foundation/evolution-go.git
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Fluxo de Trabalho de Sincronização
|
## 2. Sincronização Automática (Gitea Actions)
|
||||||
|
|
||||||
|
O workflow `.gitea/workflows/upstream-sync-check.yml` roda todo dia às 04:00 UTC
|
||||||
|
(e sob demanda em *Actions → Sincronizacao Diaria com o Upstream → Run workflow*)
|
||||||
|
e executa `scripts/upstream-sync.sh`:
|
||||||
|
|
||||||
|
1. `git fetch upstream main --tags`.
|
||||||
|
2. Avança `upstream-sync` **somente por fast-forward** (push sem force). Se o
|
||||||
|
upstream reescrever histórico, abre Issue e para.
|
||||||
|
3. Se `maintained-develop` ainda não contém o upstream, cria
|
||||||
|
`maintenance/sync-upstream-<sha7>` **a partir de `maintained-develop`** e faz
|
||||||
|
`git merge --no-ff upstream/main`. Nossas correções ficam preservadas porque o
|
||||||
|
upstream é mesclado *por cima* do nosso código, nunca o contrário.
|
||||||
|
- **Conflito:** aborta e abre Issue com os arquivos em conflito e os comandos
|
||||||
|
para resolver (seção 3 abaixo).
|
||||||
|
- **Merge limpo:** roda `go build`, `go vet`, `go test`, faz push da branch e
|
||||||
|
abre PR para `maintained-develop` com commits novos, arquivos sensíveis
|
||||||
|
alterados (Dockerfile, go.mod, `pkg/core`, licenças) e resultado dos testes.
|
||||||
|
4. Compara o `go.mau.fi/whatsmeow` do `go.mod` com `@latest` e abre Issue quando
|
||||||
|
há versão mais nova (defasagem do whatsmeow causa o erro 405).
|
||||||
|
|
||||||
|
Mesclagem automática em `maintained-develop` (opcional): crie a variável de
|
||||||
|
repositório `AUTO_MERGE_UPSTREAM=true` (*Settings → Actions → Variables*). O PR
|
||||||
|
só é mesclado se build e testes passarem. `maintained-stable` **nunca** é tocada
|
||||||
|
pela automação; a promoção e a publicação da imagem continuam manuais.
|
||||||
|
|
||||||
|
## 3. Fluxo Manual de Sincronização
|
||||||
|
|
||||||
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
|
A sincronização **NUNCA** deve sobrescrever diretamente a branch `maintained-stable` ou branches ativas de desenvolvimento sem validação.
|
||||||
|
|
||||||
@@ -57,7 +83,7 @@ git push origin upstream-sync --tags
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Integração e Análise de Impacto
|
## 4. Integração e Análise de Impacto
|
||||||
|
|
||||||
### Etapa 4: Criar branch de teste e integração
|
### Etapa 4: Criar branch de teste e integração
|
||||||
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
|
A partir de `maintained-develop`, crie uma branch de manutenção específica para a atualização:
|
||||||
@@ -80,7 +106,7 @@ Se houver conflitos:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Validação Pós-Sincronização
|
## 5. Validação Pós-Sincronização
|
||||||
|
|
||||||
Antes de propor a integração para as branches mantidas:
|
Antes de propor a integração para as branches mantidas:
|
||||||
|
|
||||||
@@ -102,7 +128,7 @@ Antes de propor a integração para as branches mantidas:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Promoção para as Branches Oficiais
|
## 6. Promoção para as Branches Oficiais
|
||||||
|
|
||||||
1. **Abra um Pull Request no Gitea:**
|
1. **Abra um Pull Request no Gitea:**
|
||||||
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
- Origem: `maintenance/sync-upstream-<nova-versao>`
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Incorpora o upstream oficial na nossa distribuicao SEM sobrescrever nada nosso.
|
||||||
|
#
|
||||||
|
# Fluxo (idempotente, seguro para rodar todo dia):
|
||||||
|
# 1. fetch upstream/main + tags
|
||||||
|
# 2. fast-forward de origin/upstream-sync (push sem force: se nao for ff, falha e abre issue)
|
||||||
|
# 3. merge upstream/main -> branch maintenance/sync-upstream-<sha> criada a partir de maintained-develop
|
||||||
|
# - conflito -> aborta, abre Issue listando os arquivos em conflito
|
||||||
|
# - limpo -> go build / vet / test, push da branch e PR para maintained-develop
|
||||||
|
# 4. verifica se ha versao mais nova do go.mau.fi/whatsmeow e abre Issue de aviso
|
||||||
|
#
|
||||||
|
# maintained-develop e maintained-stable NUNCA recebem push deste script.
|
||||||
|
# Opcional: AUTO_MERGE=true faz merge automatico do PR em maintained-develop quando
|
||||||
|
# build e testes passam (nunca em maintained-stable).
|
||||||
|
#
|
||||||
|
# Variaveis: GITEA_URL, REPO (owner/name), GITEA_TOKEN, UPSTREAM_URL, BASE_BRANCH, AUTO_MERGE
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
GITEA_URL="${GITEA_URL:-https://git.jf.eng.br}"
|
||||||
|
REPO="${REPO:-jfeng/EvoGO}"
|
||||||
|
UPSTREAM_URL="${UPSTREAM_URL:-https://github.com/evolution-foundation/evolution-go.git}"
|
||||||
|
UPSTREAM_BRANCH="${UPSTREAM_BRANCH:-main}"
|
||||||
|
BASE_BRANCH="${BASE_BRANCH:-maintained-develop}"
|
||||||
|
MIRROR_BRANCH="${MIRROR_BRANCH:-upstream-sync}"
|
||||||
|
AUTO_MERGE="${AUTO_MERGE:-false}"
|
||||||
|
API="${GITEA_URL%/}/api/v1/repos/${REPO}"
|
||||||
|
|
||||||
|
log() { echo "[upstream-sync] $*"; }
|
||||||
|
|
||||||
|
api() { # api METHOD PATH [JSON]
|
||||||
|
local method="$1" path="$2" data="${3:-}"
|
||||||
|
if [ -z "${GITEA_TOKEN:-}" ]; then
|
||||||
|
log "GITEA_TOKEN ausente; chamada ${method} ${path} ignorada"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if [ -n "$data" ]; then
|
||||||
|
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json" \
|
||||||
|
--data "$data" "${API}${path}"
|
||||||
|
else
|
||||||
|
curl -fsS -X "$method" -H "Authorization: token ${GITEA_TOKEN}" "${API}${path}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
json_payload() { # json_payload key=file|key=@string ... -> JSON object
|
||||||
|
python3 - "$@" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
out = {}
|
||||||
|
for arg in sys.argv[1:]:
|
||||||
|
k, v = arg.split("=", 1)
|
||||||
|
if v.startswith("@"):
|
||||||
|
out[k] = v[1:]
|
||||||
|
else:
|
||||||
|
out[k] = open(v, encoding="utf-8").read()
|
||||||
|
print(json.dumps(out))
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
open_issue_once() { # open_issue_once TITLE BODY_FILE
|
||||||
|
local title="$1" body_file="$2" existing
|
||||||
|
existing=$(api GET "/issues?state=open&type=issues&limit=50" | python3 -c "
|
||||||
|
import json,sys
|
||||||
|
t=sys.argv[1]
|
||||||
|
print(next((str(i['number']) for i in json.load(sys.stdin) if i['title']==t),''))" "$title" || true)
|
||||||
|
if [ -n "$existing" ]; then
|
||||||
|
log "Issue ja aberta (#${existing}): ${title}"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
api POST "/issues" "$(json_payload "title=@${title}" "body=${body_file}")" >/dev/null && log "Issue aberta: ${title}"
|
||||||
|
}
|
||||||
|
|
||||||
|
git config user.name >/dev/null || git config user.name "EvoGO Upstream Bot"
|
||||||
|
git config user.email >/dev/null || git config user.email "[email protected]"
|
||||||
|
|
||||||
|
git remote get-url upstream >/dev/null 2>&1 || git remote add upstream "$UPSTREAM_URL"
|
||||||
|
git fetch --quiet upstream "$UPSTREAM_BRANCH" --tags
|
||||||
|
git fetch --quiet origin
|
||||||
|
|
||||||
|
UP_SHA=$(git rev-parse "upstream/${UPSTREAM_BRANCH}")
|
||||||
|
UP_SHORT=$(git rev-parse --short=7 "$UP_SHA")
|
||||||
|
REPORT=$(mktemp)
|
||||||
|
|
||||||
|
# --- 1. espelho upstream-sync (fast-forward apenas) -----------------------------
|
||||||
|
if git rev-parse --verify --quiet "origin/${MIRROR_BRANCH}" >/dev/null; then
|
||||||
|
if git merge-base --is-ancestor "$UP_SHA" "origin/${MIRROR_BRANCH}"; then
|
||||||
|
log "${MIRROR_BRANCH} ja contem upstream ${UP_SHORT}"
|
||||||
|
elif git merge-base --is-ancestor "origin/${MIRROR_BRANCH}" "$UP_SHA"; then
|
||||||
|
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
|
||||||
|
log "${MIRROR_BRANCH} avancada (fast-forward) para ${UP_SHORT}"
|
||||||
|
else
|
||||||
|
printf '%s\n' "A branch \`${MIRROR_BRANCH}\` divergiu de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT})." \
|
||||||
|
"" "Nao foi feito push forcado. Verifique se o upstream reescreveu historico antes de prosseguir." > "$REPORT"
|
||||||
|
open_issue_once "upstream-sync: ${MIRROR_BRANCH} divergiu do upstream" "$REPORT" || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
git push origin "${UP_SHA}:refs/heads/${MIRROR_BRANCH}"
|
||||||
|
fi
|
||||||
|
# Tags do upstream (sem force: tags locais com mesmo nome nunca sao sobrescritas)
|
||||||
|
git push --quiet origin --tags 2>/dev/null || log "algumas tags nao foram enviadas (ja existem com outro alvo)"
|
||||||
|
|
||||||
|
# --- 2. ha algo novo para incorporar? ----------------------------------------------
|
||||||
|
if git merge-base --is-ancestor "$UP_SHA" "origin/${BASE_BRANCH}"; then
|
||||||
|
log "${BASE_BRANCH} ja incorpora upstream ${UP_SHORT}; nada a fazer"
|
||||||
|
else
|
||||||
|
SYNC_BRANCH="maintenance/sync-upstream-${UP_SHORT}"
|
||||||
|
if git rev-parse --verify --quiet "origin/${SYNC_BRANCH}" >/dev/null; then
|
||||||
|
log "branch ${SYNC_BRANCH} ja existe (PR pendente); nada a fazer"
|
||||||
|
else
|
||||||
|
NEW_COMMITS=$(git log --oneline --no-merges "origin/${BASE_BRANCH}..${UP_SHA}" | head -50)
|
||||||
|
SENSITIVE=$(git diff --stat "$(git merge-base "origin/${BASE_BRANCH}" "$UP_SHA")" "$UP_SHA" -- \
|
||||||
|
Dockerfile docker-compose* .env.example go.mod pkg/core cmd LICENSE NOTICE TRADEMARKS.md || true)
|
||||||
|
|
||||||
|
git checkout --quiet -B "$SYNC_BRANCH" "origin/${BASE_BRANCH}"
|
||||||
|
if ! git merge --no-ff --no-edit -m "sync: merge upstream ${UPSTREAM_BRANCH} ${UP_SHORT} into ${BASE_BRANCH}" "$UP_SHA"; then
|
||||||
|
CONFLICTS=$(git diff --name-only --diff-filter=U)
|
||||||
|
git merge --abort
|
||||||
|
{
|
||||||
|
echo "O merge automatico de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\` gerou conflitos."
|
||||||
|
echo; echo "## Arquivos em conflito"; echo '```'; echo "$CONFLICTS"; echo '```'
|
||||||
|
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
|
||||||
|
echo; echo "## Como resolver"
|
||||||
|
echo '```bash'
|
||||||
|
echo "git fetch origin && git fetch upstream"
|
||||||
|
echo "git checkout -b ${SYNC_BRANCH} origin/${BASE_BRANCH}"
|
||||||
|
echo "git merge upstream/${UPSTREAM_BRANCH} # resolver conflitos preservando as correcoes EvoGO"
|
||||||
|
echo "go build ./... && go vet ./... && go test ./..."
|
||||||
|
echo "git push origin ${SYNC_BRANCH} # e abrir PR para ${BASE_BRANCH}"
|
||||||
|
echo '```'
|
||||||
|
echo; echo "Veja docs/maintenance/UPSTREAM_SYNC.md."
|
||||||
|
} > "$REPORT"
|
||||||
|
open_issue_once "upstream-sync: conflito ao incorporar upstream ${UP_SHORT}" "$REPORT" || true
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
TEST_STATUS="nao executado (Go indisponivel)"
|
||||||
|
TESTS_OK=false
|
||||||
|
if command -v go >/dev/null 2>&1; then
|
||||||
|
if go build ./... > /tmp/sync-build.log 2>&1 && go vet ./... >> /tmp/sync-build.log 2>&1 \
|
||||||
|
&& go test ./... >> /tmp/sync-build.log 2>&1; then
|
||||||
|
TEST_STATUS="OK (go build, go vet, go test)"
|
||||||
|
TESTS_OK=true
|
||||||
|
else
|
||||||
|
TEST_STATUS="FALHOU — ver log abaixo"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
git push --quiet origin "$SYNC_BRANCH"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "Incorporacao automatica de \`upstream/${UPSTREAM_BRANCH}\` (${UP_SHORT}) em \`${BASE_BRANCH}\`."
|
||||||
|
echo
|
||||||
|
echo "O merge foi feito por cima da nossa branch: todas as correcoes EvoGO continuam presentes."
|
||||||
|
echo
|
||||||
|
echo "**Build/testes:** ${TEST_STATUS}"
|
||||||
|
echo; echo "## Commits novos do upstream"; echo '```'; echo "$NEW_COMMITS"; echo '```'
|
||||||
|
if [ -n "$SENSITIVE" ]; then
|
||||||
|
echo; echo "## Arquivos sensiveis alterados (revisar com atencao)"; echo '```'; echo "$SENSITIVE"; echo '```'
|
||||||
|
fi
|
||||||
|
if [ "$TESTS_OK" != true ] && [ -f /tmp/sync-build.log ]; then
|
||||||
|
echo; echo "## Log de build/testes (final)"; echo '```'; tail -60 /tmp/sync-build.log; echo '```'
|
||||||
|
fi
|
||||||
|
echo; echo "## Checklist antes do merge"
|
||||||
|
echo "- [ ] Revisar commits e arquivos sensiveis"
|
||||||
|
echo "- [ ] Verificar mudancas de schema (whatsmeow / SQLite / Postgres)"
|
||||||
|
echo "- [ ] Testar imagem de homologacao (docs/maintenance/WHATSAPP_COMPATIBILITY.md)"
|
||||||
|
} > "$REPORT"
|
||||||
|
|
||||||
|
PR_JSON=$(api POST "/pulls" "$(json_payload "title=@sync: incorporar upstream ${UP_SHORT}" \
|
||||||
|
"head=@${SYNC_BRANCH}" "base=@${BASE_BRANCH}" "body=${REPORT}")" || true)
|
||||||
|
PR_NUMBER=$(printf '%s' "$PR_JSON" | python3 -c "import json,sys
|
||||||
|
try: print(json.load(sys.stdin)['number'])
|
||||||
|
except Exception: print('')")
|
||||||
|
log "PR aberto: #${PR_NUMBER:-?}"
|
||||||
|
|
||||||
|
if [ "$AUTO_MERGE" = "true" ] && [ "$TESTS_OK" = true ] && [ -n "$PR_NUMBER" ]; then
|
||||||
|
api POST "/pulls/${PR_NUMBER}/merge" '{"Do":"merge","delete_branch_after_merge":true}' >/dev/null \
|
||||||
|
&& log "PR #${PR_NUMBER} mesclado automaticamente em ${BASE_BRANCH}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 3. whatsmeow mais novo disponivel? -------------------------------------------
|
||||||
|
if command -v go >/dev/null 2>&1; then
|
||||||
|
git checkout --quiet "origin/${BASE_BRANCH}"
|
||||||
|
CUR_WM=$(awk '$1=="go.mau.fi/whatsmeow"{print $2}' go.mod)
|
||||||
|
LATEST_WM=$(GOFLAGS=-mod=mod go list -m -f '{{.Version}}' go.mau.fi/whatsmeow@latest 2>/dev/null || true)
|
||||||
|
if [ -n "$LATEST_WM" ] && [ -n "$CUR_WM" ] && [ "$LATEST_WM" != "$CUR_WM" ]; then
|
||||||
|
{
|
||||||
|
echo "Ha uma versao mais nova de \`go.mau.fi/whatsmeow\`."
|
||||||
|
echo
|
||||||
|
echo "- Atual (${BASE_BRANCH}): \`${CUR_WM}\`"
|
||||||
|
echo "- Mais recente: \`${LATEST_WM}\`"
|
||||||
|
echo
|
||||||
|
echo "Defasagem do whatsmeow e a principal causa do erro **Client outdated (405)**."
|
||||||
|
echo "Atualize em uma branch \`maintenance/whatsmeow-<data>\`:"
|
||||||
|
echo '```bash'
|
||||||
|
echo "go get go.mau.fi/whatsmeow@latest && go mod tidy"
|
||||||
|
echo "go build ./... && go vet ./... && go test ./..."
|
||||||
|
echo '```'
|
||||||
|
} > "$REPORT"
|
||||||
|
open_issue_once "whatsmeow: atualizacao disponivel (${LATEST_WM})" "$REPORT" || true
|
||||||
|
else
|
||||||
|
log "whatsmeow em dia (${CUR_WM})"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -f "$REPORT"
|
||||||
|
log "concluido"
|
||||||
Reference in new issue
Block a user