Repository navigation
Expand file tree
/
Copy pathpublish.ps1
More file actions
222 lines (200 loc) · 9.3 KB
/
Copy pathpublish.ps1
File metadata and controls
222 lines (200 loc) · 9.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<#
.SYNOPSIS
Publica a SDK C++ da APIBrasil no GitHub (push do branch + tag + release).
.DESCRIPTION
Fluxo:
1. Detecta a versao (de include/apibrasil/version.hpp) e monta a tag vX.Y.Z.
2. (Opcional) Compila e roda os testes como gate de qualidade.
3. Garante a tag anotada apontando para o HEAD atual.
4. Faz push do branch e da tag para o remoto.
5. Se o gh CLI estiver instalado, cria a Release formal com as notas do CHANGELOG.
Use -Force quando precisar REESCREVER o historico remoto (ex.: remover um
commit indevido). Isso usa 'git push --force-with-lease'.
.EXAMPLE
.\publish.ps1
Publica a versao atual (push normal, sem reescrever historico).
.EXAMPLE
.\publish.ps1 -Force
Publica reescrevendo o historico do branch remoto (force-with-lease).
.EXAMPLE
.\publish.ps1 -DryRun
Mostra o que faria, sem enviar nada ao remoto.
#>
[CmdletBinding()]
param(
[string]$Version, # ex.: "0.0.1" (padrao: lido de version.hpp)
[string]$Remote = "origin",
[string]$Branch = "main",
[string]$SquashFrom, # colapsa o historico desde esta ref num unico commit limpo
[switch]$SkipBuild, # pula a etapa de build/testes
[switch]$Force, # reescreve o historico remoto (force-with-lease)
[switch]$DryRun # nao envia nada ao remoto
)
$ErrorActionPreference = 'Stop'
function Info($m) { Write-Host "==> $m" -ForegroundColor Cyan }
function Good($m) { Write-Host "OK $m" -ForegroundColor Green }
function Warn($m) { Write-Host "!! $m" -ForegroundColor Yellow }
function Die($m) { Write-Host "ERRO: $m" -ForegroundColor Red; exit 1 }
function Invoke-GitOrDie {
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$GitArgs)
& git @GitArgs
if ($LASTEXITCODE -ne 0) { Die "git $($GitArgs -join ' ') falhou (exit $LASTEXITCODE)" }
}
# --- 0. Ir para a raiz do repositorio (diretorio deste script) ----------------
$RepoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $RepoRoot
if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Die "git nao encontrado no PATH." }
& git rev-parse --is-inside-work-tree *> $null
if ($LASTEXITCODE -ne 0) { Die "Este diretorio nao e um repositorio git: $RepoRoot" }
# --- 1. Versao / tag ----------------------------------------------------------
if (-not $Version) {
$verFile = Join-Path $RepoRoot "include\apibrasil\version.hpp"
if (-not (Test-Path $verFile)) { Die "version.hpp nao encontrado; use -Version." }
$m = Select-String -Path $verFile -Pattern 'APIBRASIL_SDK_VERSION\s+"([^"]+)"'
if (-not $m) { Die "Nao consegui ler a versao de version.hpp; use -Version." }
$Version = $m.Matches[0].Groups[1].Value
}
$Tag = "v$Version"
Info "Versao: $Version Tag: $Tag Remoto: $Remote/$Branch"
# Arvore de trabalho limpa? (ignora arquivos nao rastreados, ex.: build/).
# Com -SquashFrom nao checamos: o objetivo e justamente colapsar as mudancas
# atuais em um unico commit de release.
if (-not $SquashFrom) {
$dirty = & git status --porcelain --untracked-files=no
if ($dirty) {
Warn "Ha alteracoes rastreadas nao commitadas:"
$dirty | ForEach-Object { Write-Host " $_" }
Die "Faca commit ou stash antes de publicar."
}
}
# --- 1b. (Opcional) Colapsar o historico em um unico commit limpo ------------
# Util para remover commits indevidos: reescreve tudo desde <SquashFrom> como um
# unico commit de release (sem co-autor, sem merges). Combine com -Force.
if ($SquashFrom) {
& git rev-parse --verify --quiet "$SquashFrom^{commit}" *> $null
if ($LASTEXITCODE -ne 0) { Die "Ref invalida para -SquashFrom: $SquashFrom" }
Info "Colapsando o historico desde $SquashFrom em um unico commit limpo..."
Invoke-GitOrDie add -A
Invoke-GitOrDie reset --soft $SquashFrom
$msg = "release: v$Version`n`nPrimeira versao publica da SDK oficial C++ da APIBrasil."
$msgFile = [System.IO.Path]::GetTempFileName()
[System.IO.File]::WriteAllText($msgFile, $msg, (New-Object System.Text.UTF8Encoding($false)))
& git commit -F $msgFile
$commitOk = ($LASTEXITCODE -eq 0)
Remove-Item $msgFile -ErrorAction SilentlyContinue
if (-not $commitOk) { Die "Falha ao criar o commit do squash (nada para commitar?)." }
Invoke-GitOrDie tag -fa $Tag -m "APIBrasil SDK C++ $Tag"
Good "Historico colapsado em $(& git rev-parse --short HEAD) (tag $Tag reposicionada)."
}
# --- 2. Build + testes (gate opcional) ---------------------------------------
if (-not $SkipBuild) {
$cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source
if (-not $cmake) {
$vsCmake = "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe"
if (Test-Path $vsCmake) { $cmake = $vsCmake }
}
if ($cmake) {
Info "Compilando e testando (use -SkipBuild para pular)..."
& $cmake -S $RepoRoot -B (Join-Path $RepoRoot "build")
if ($LASTEXITCODE -ne 0) { Die "cmake configure falhou." }
& $cmake --build (Join-Path $RepoRoot "build") --config Release
if ($LASTEXITCODE -ne 0) { Die "build falhou." }
$testExe = Get-ChildItem -Path (Join-Path $RepoRoot "build") -Recurse -Filter "apibrasil_tests.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($testExe) {
& $testExe.FullName
if ($LASTEXITCODE -ne 0) { Die "testes falharam." }
Good "Build e testes passaram."
} else {
Warn "Executavel de testes nao encontrado; build OK."
}
} else {
Warn "cmake nao encontrado; pulando build/testes."
}
} else {
Warn "Build/testes pulados (-SkipBuild)."
}
# --- 3. Garantir a tag anotada -----------------------------------------------
$existingTag = & git tag --list $Tag
if ($existingTag) {
$tagCommit = & git rev-list -n 1 $Tag
$headCommit = & git rev-parse HEAD
if ($tagCommit -ne $headCommit) {
Warn "A tag $Tag existe mas aponta para outro commit ($tagCommit) e nao para o HEAD ($headCommit)."
$ans = Read-Host "Mover a tag $Tag para o HEAD atual? (s/N)"
if ($ans -match '^[sSyY]') {
Invoke-GitOrDie tag -fa $Tag -m "APIBrasil SDK C++ $Tag"
Good "Tag $Tag movida para o HEAD."
}
} else {
Info "Tag $Tag ja aponta para o HEAD."
}
} else {
Invoke-GitOrDie tag -a $Tag -m "APIBrasil SDK C++ $Tag - versao inicial"
Good "Tag anotada $Tag criada."
}
# --- 4. Confirmacao ----------------------------------------------------------
Info "Historico local:"
& git log --oneline --graph --decorate -5
if ($DryRun) {
Warn "DRY-RUN: nada sera enviado ao remoto. Comandos que seriam executados:"
$pushCmd = if ($Force) { "git push --force-with-lease $Remote $Branch" } else { "git push $Remote $Branch" }
Write-Host " $pushCmd"
Write-Host " git push $Remote $Tag"
exit 0
}
if ($Force) {
Warn "MODO -Force: o historico do branch remoto '$Remote/$Branch' sera REESCRITO (force-with-lease). Irreversivel."
}
$confirm = Read-Host "Publicar $Tag em $Remote/$Branch agora? (s/N)"
if ($confirm -notmatch '^[sSyY]') { Warn "Cancelado. Nada foi enviado."; exit 0 }
# --- 5. Push do branch -------------------------------------------------------
if ($Force) {
Info "Push do branch (force-with-lease)..."
& git push --force-with-lease $Remote $Branch
} else {
Info "Push do branch..."
& git push $Remote $Branch
}
if ($LASTEXITCODE -ne 0) {
Warn "O push do branch falhou. Se o remoto divergiu (nao-fast-forward) e voce quer"
Warn "reescrever o historico (ex.: remover um commit), rode: .\publish.ps1 -Force"
Die "push do branch falhou."
}
Good "Branch publicado."
# --- 6. Push da tag ----------------------------------------------------------
Info "Push da tag $Tag..."
if ($Force) { & git push --force $Remote $Tag } else { & git push $Remote $Tag }
if ($LASTEXITCODE -ne 0) { Die "push da tag falhou." }
Good "Tag $Tag publicada."
# --- 7. Release formal no GitHub (se o gh estiver instalado) ------------------
$gh = (Get-Command gh -ErrorAction SilentlyContinue).Source
if ($gh) {
Info "Criando a Release no GitHub via gh..."
$notes = ""
$cl = Join-Path $RepoRoot "CHANGELOG.md"
if (Test-Path $cl) {
$collect = $false; $buf = @()
foreach ($line in Get-Content $cl) {
if ($line -match '^\s*##\s*\[') {
if ($collect) { break }
if ($line -match [regex]::Escape("[$Version]")) { $collect = $true; continue }
} elseif ($collect) { $buf += $line }
}
$notes = ($buf -join "`n").Trim()
}
$notesFile = New-TemporaryFile
if (-not $notes) { $notes = "APIBrasil SDK C++ $Tag" }
Set-Content -Path $notesFile -Value $notes -Encoding UTF8
& gh release create $Tag --title "APIBrasil SDK C++ $Tag" --notes-file $notesFile
Remove-Item $notesFile -ErrorAction SilentlyContinue
if ($LASTEXITCODE -eq 0) { Good "Release $Tag criada no GitHub." }
else { Warn "Falha ao criar a Release via gh (a tag ja foi publicada)." }
} else {
$url = & git remote get-url $Remote 2>$null
if ($url) {
$url = $url -replace '\.git$', ''
Warn "gh CLI nao instalado. Crie a Release formal (opcional) em:"
Write-Host " $url/releases/new?tag=$Tag"
}
}
Good "Publicacao concluida: $Tag"