Nova atualização sem pedir credenciais do git

This commit is contained in:
Ricardo Sardá
2025-08-21 11:28:58 -03:00
parent 68a9d9934f
commit 5bd037dc8e

View File

@@ -1,25 +1,28 @@
<# <#
Atualiza C:\plhDownloads\ com o conteúdo do repositório (branch main) Atualiza C:\PilotDownloads\ com o conteúdo do repositório (branch main)
https://gitea.magicis.com.br/PilotSupport/vlt-install e executa pilot_install.ps1 https://gitea.magicis.com.br/PilotSupport/vlt-install e executa pilot_install.ps1
Requisitos: Recursos:
- PowerShell com permissões para escrever em C:\plhDownloads\ - Instala/atualiza Git via winget
- Preferível executar em janela elevada (winget pode pedir UAC) - Evita abrir navegador (sem prompts do GCM)
- Suporte a token do Gitea (param ou arquivo)
O script: - Copia por cima (não espelha)
1) Garante winget e usa-o para instalar/atualizar Git (Git.Git).
2) Clona/atualiza o repo em pasta temporária.
3) Copia por cima (sem /MIR) para C:\plhDownloads\ (exclui .git).
4) Executa pilot_install.ps1
#> #>
param(
[string]$GitUser, # opcional: usuário do Gitea
[string]$GitToken, # opcional: PAT do Gitea
[string]$GitTokenPath # opcional: caminho de arquivo contendo somente o token
)
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
# ===== Configurações ===== # ===== Configurações =====
$RepoUrl = 'https://gitea.magicis.com.br/PilotSupport/vlt-install' $RepoUrl = 'https://gitea.magicis.com.br/PilotSupport/vlt-install' # sem credenciais na URL
$Branch = 'main' # sempre main $Branch = 'main'
$TargetDir = 'C:\PilotDownloads' $TargetDir = 'C:\PilotDownloads'
$WorkDir = Join-Path $env:TEMP 'vlt-install_repo' $WorkDir = Join-Path $env:TEMP 'vlt-install_repo'
$CopyLog = Join-Path $env:TEMP 'vlt-install_copy.log'
# ===== Utilitárias ===== # ===== Utilitárias =====
function Write-Info($m){ Write-Host "[INFO ] $m" -ForegroundColor Cyan } function Write-Info($m){ Write-Host "[INFO ] $m" -ForegroundColor Cyan }
@@ -33,44 +36,36 @@ function Ensure-Dir([string]$Path){
} }
} }
function Test-Winget { function Test-Winget { [bool](Get-Command winget -ErrorAction SilentlyContinue) }
return [bool](Get-Command winget -ErrorAction SilentlyContinue)
}
function Ensure-Git-WithWinget { function Ensure-Git-WithWinget {
if (-not (Test-Winget)) { if (-not (Test-Winget)) {
Write-Err "winget não encontrado. Instale o 'App Installer' da Microsoft Store para habilitar o winget." Write-Err "winget não encontrado. Instale o 'App Installer' pela Microsoft Store para habilitar o winget."
throw "winget ausente" throw "winget ausente"
} }
Write-Info "Verificando Git via winget..." Write-Info "Verificando Git via winget..."
$argsCommon = @('--accept-package-agreements','--accept-source-agreements') $argsCommon = @('--accept-package-agreements','--accept-source-agreements','--silent')
# Detecta se Git está instalado # Detecta se Git está instalado
$gitInstalled = $false $gitInstalled = $false
try { try {
# 'winget list' retorna errolevel 0 mesmo sem pacote; interpretamos saída $list = winget list --id Git.Git -e @argsCommon 2>$null
$list = winget list --id Git.Git -e 2>$null
if ($list -match 'Git\s+Git') { $gitInstalled = $true } if ($list -match 'Git\s+Git') { $gitInstalled = $true }
} catch { } } catch { }
if ($gitInstalled) { if ($gitInstalled) {
Write-Info "Atualizando Git (se necessário)..." Write-Info "Atualizando Git (se necessário)..."
# silencia prompts; se não houver upgrade disponível, winget finaliza OK. & winget upgrade --id Git.Git -e @argsCommon | Out-Null
winget upgrade --id Git.Git -e @argsCommon --silent | Out-Null
} else { } else {
Write-Info "Instalando Git..." Write-Info "Instalando Git..."
winget install --id Git.Git -e @argsCommon --silent | Out-Null & winget install --id Git.Git -e @argsCommon | Out-Null
} }
# Garante que o git esteja acessível # Garante PATH do git
$gitCmd = Get-Command git -ErrorAction SilentlyContinue if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
if (-not $gitCmd) {
# tenta caminho usual
$maybeGit = 'C:\Program Files\Git\cmd\git.exe' $maybeGit = 'C:\Program Files\Git\cmd\git.exe'
if (Test-Path $maybeGit) { if (Test-Path $maybeGit) { $env:Path = "C:\Program Files\Git\cmd;$env:Path" }
$env:Path = "C:\Program Files\Git\cmd;$env:Path"
}
} }
$ver = git --version 2>$null $ver = git --version 2>$null
@@ -78,39 +73,82 @@ function Ensure-Git-WithWinget {
Write-Ok "Git pronto: $ver" Write-Ok "Git pronto: $ver"
} }
# ===== Fluxo principal ===== function Get-GitTokenEffective {
try { if ($GitToken) { return $GitToken }
Ensure-Git-WithWinget if ($GitTokenPath) {
if (-not (Test-Path -LiteralPath $GitTokenPath)) {
throw "Arquivo de token não encontrado: $GitTokenPath"
}
return (Get-Content -LiteralPath $GitTokenPath -Raw).Trim()
}
return $null
}
function Get-BasicAuthHeader([string]$user,[string]$token){
if (-not $user -or -not $token) { return $null }
$bytes = [Text.Encoding]::ASCII.GetBytes("$user`:$token")
$base64 = [Convert]::ToBase64String($bytes)
return "Authorization: Basic $base64"
}
function Get-GitCommonArgs {
param([string]$AuthHeader)
# Evita prompts/UI/navegador e askpass
$args = @(
'-c','credential.helper=',
'-c','credential.interactive=never',
'-c','core.askPass='
)
# Se fornecer header, usa-o nesta chamada (não grava no .git/config)
if ($AuthHeader) {
$args += @('-c',"http.extraHeader=$AuthHeader")
}
return ,$args
}
# ===== Início =====
try {
# Auto-desbloqueia este arquivo (elimina marca de internet se houver)
try { Unblock-File -LiteralPath $MyInvocation.MyCommand.Path -ErrorAction SilentlyContinue } catch { }
Ensure-Git-WithWinget
Ensure-Dir $TargetDir Ensure-Dir $TargetDir
# Prepara/atualiza repositório no diretório de trabalho # Prepara credenciais (opcionais)
$EffectiveToken = Get-GitTokenEffective
if ($GitUser -and -not $EffectiveToken) {
Write-Warn "GitUser informado mas nenhum token fornecido. Continuação sem autenticação."
}
$AuthHeader = $null
if ($GitUser -and $EffectiveToken) {
$AuthHeader = Get-BasicAuthHeader -user $GitUser -token $EffectiveToken
Write-Info "Usando autenticação via header (sem gravar credenciais em .git/config)."
}
# Nunca abrir prompts/navegador
$env:GIT_TERMINAL_PROMPT = '0'
# Clone/Update
if (Test-Path (Join-Path $WorkDir '.git')) { if (Test-Path (Join-Path $WorkDir '.git')) {
Write-Info "Atualizando repositório existente em $WorkDir ..." Write-Info "Atualizando repositório em $WorkDir ..."
Push-Location $WorkDir Push-Location $WorkDir
try { git remote set-url origin $RepoUrl | Out-Null } catch { } try { & git (Get-GitCommonArgs -AuthHeader $AuthHeader) remote set-url origin $RepoUrl | Out-Null } catch { }
git fetch --all --prune & git (Get-GitCommonArgs -AuthHeader $AuthHeader) fetch --all --prune
git checkout $Branch & git (Get-GitCommonArgs -AuthHeader $AuthHeader) checkout $Branch
git reset --hard "origin/$Branch" & git (Get-GitCommonArgs -AuthHeader $AuthHeader) reset --hard "origin/$Branch"
Pop-Location Pop-Location
} else { } else {
Write-Info "Clonando repositório (branch $Branch) para $WorkDir ..." Write-Info "Clonando repositório (branch $Branch) para $WorkDir ..."
try { Remove-Item -LiteralPath $WorkDir -Recurse -Force -ErrorAction SilentlyContinue } catch { } try { Remove-Item -LiteralPath $WorkDir -Recurse -Force -ErrorAction SilentlyContinue } catch { }
Ensure-Dir $WorkDir Ensure-Dir $WorkDir
git clone --depth 1 --branch $Branch $RepoUrl $WorkDir & git (Get-GitCommonArgs -AuthHeader $AuthHeader) clone --depth 1 --branch $Branch $RepoUrl $WorkDir
Write-Ok "Clone concluído." Write-Ok "Clone concluído."
} }
# Copiar por cima para o destino (sem espelhar/sem apagar o que já existe) # Copiar por cima (sem espelhar)
Write-Info "Copiando arquivos para $TargetDir (sem espelhar)..." Write-Info "Copiando arquivos para $TargetDir (sem espelhar)..."
$log = Join-Path $env:TEMP 'vlt-install_copy.log'
# Robocopy:
# /E -> inclui subpastas (inclui vazias)
# /IS -> inclui arquivos “iguais” (força overwrite)
# /IT -> inclui arquivos “tweak”
# /XO -> (opcional) pula arquivos mais antigos na origem; REMOVIDO para forçar overwrite
# /NFL /NDL /NP -> logs mais limpos
$rc = robocopy ` $rc = robocopy `
$WorkDir ` $WorkDir `
$TargetDir ` $TargetDir `
@@ -118,13 +156,13 @@ try {
/E /IS /IT /R:1 /W:1 /NFL /NDL /NP ` /E /IS /IT /R:1 /W:1 /NFL /NDL /NP `
/XD ".git" ` /XD ".git" `
/XF ".gitignore" ".gitattributes" ` /XF ".gitignore" ".gitattributes" `
/LOG:$log /LOG:$CopyLog
if ($LASTEXITCODE -ge 8) { if ($LASTEXITCODE -ge 8) {
Write-Err "Falha ao copiar arquivos. Veja o log: $log" Write-Err "Falha ao copiar arquivos. Veja o log: $CopyLog"
exit $LASTEXITCODE exit $LASTEXITCODE
} else { } else {
Write-Ok "Cópia finalizada. (código robocopy: $LASTEXITCODE) Log: $log" Write-Ok "Cópia finalizada. (código robocopy: $LASTEXITCODE) Log: $CopyLog"
} }
# Executa o instalador # Executa o instalador
@@ -151,4 +189,7 @@ try {
} catch { } catch {
Write-Err ("Erro: " + $_.Exception.Message) Write-Err ("Erro: " + $_.Exception.Message)
exit 1 exit 1
} finally {
# Limpa variáveis sensíveis do ambiente
Remove-Item Env:\GIT_TERMINAL_PROMPT -ErrorAction SilentlyContinue
} }