#!/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- 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 "evogo-bot@noreply.local" 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-\`:" 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"