maestri-remote/.context/skills/azure-boards-work-item-and-pr/scripts/attach-file.mjs

105 lines
5.1 KiB
JavaScript

#!/usr/bin/env node
// Anexa um arquivo (spec/relatório/evidência) a um work item do Azure Boards, sem duplicar.
// Uso:
// node attach-file.mjs --org <org> --project <projeto> --id <workItemId> --file <caminho> [--name <nome-do-anexo>] [--dry-run]
// Passos: (0) checa se já existe anexo com o mesmo nome e, se existir, não faz nada; (1) faz upload do
// arquivo bruto em _apis/wit/attachments; (2) vincula a url devolvida ao work item via PATCH
// (relations/-, rel=AttachedFile); (3) relê as relações e confirma o vínculo.
// --dry-run faz só a checagem (0) e mostra o que seria enviado; sai ANTES do upload, porque o upload
// sozinho já é escrita (cria um blob órfão na org).
// Requer Node 18+ (fetch nativo) e `az` autenticado. Sem dependências npm.
import { readFileSync } from 'node:fs';
import { basename } from 'node:path';
import { azDevOpsToken, isLoginPage, loginPageMessage } from '../../../scripts/az-devops-token.mjs';
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith('--')) continue;
const key = a.slice(2);
const next = argv[i + 1];
if (next === undefined || next.startsWith('--')) out[key] = true;
else { out[key] = next; i++; }
}
return out;
}
// Sem process.exit(): no Windows, sair à força com handles do fetch abertos derruba o Node (assert do libuv).
class Fail extends Error {}
class UsageFail extends Fail {}
function fail(msg) { throw new Fail(msg); }
const USAGE = 'uso: node attach-file.mjs --org <org> --project <projeto> --id <workItemId> --file <caminho> [--name <nome-do-anexo>] [--dry-run]';
// --help/-h: uso no stdout e código 0, antes de validar qualquer parâmetro.
if (process.argv.slice(2).some((a) => a === '--help' || a === '-h')) { console.log(USAGE); process.exit(0); }
async function getToken(org) {
// Pedido no tenant da organização (ver az-devops-token.mjs); a falha já traz o `az login` certo.
try { return await azDevOpsToken(org); } catch (e) { return fail(e.message); }
}
async function call(method, url, token, body, contentType) {
const res = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + token, ...(contentType ? { 'Content-Type': contentType } : {}) },
body,
});
// Token de outro tenant: o fetch segue o 302 para a página de login e devolve 203 com ok=true.
if (isLoginPage(res)) fail(await loginPageMessage(res, url, token));
const text = await res.text();
if (!res.ok) fail(`${method} ${url.split('?')[0]} -> HTTP ${res.status}: ${text.slice(0, 500)}`);
return text ? JSON.parse(text) : null;
}
const attachedNames = (wi) => (wi.relations || [])
.filter((r) => r.rel === 'AttachedFile')
.map((r) => r.attributes && r.attributes.name);
async function main() {
const args = parseArgs(process.argv.slice(2));
for (const k of ['org', 'project', 'id', 'file']) if (!args[k] || args[k] === true) throw new UsageFail(`falta --${k}.`);
const org = String(args.org).replace(/\/+$/, '');
const orgUrl = org.startsWith('http') ? org : 'https://dev.azure.com/' + org;
const projUrl = `${orgUrl}/${encodeURIComponent(args.project)}`;
const fileName = typeof args.name === 'string' ? args.name : basename(args.file);
const content = readFileSync(args.file);
const wiUrl = `${projUrl}/_apis/wit/workitems/${args.id}`;
const token = await getToken(org);
// 0. Checagem prévia: evita anexo duplicado.
const before = await call('GET', `${wiUrl}?$expand=relations&api-version=7.1`, token);
if (attachedNames(before).includes(fileName)) {
console.log(`O arquivo ${fileName} já está anexado ao work item ${args.id}. Nada a fazer.`);
return;
}
if (args['dry-run']) {
console.log(`[dry-run] ${fileName} ainda não está anexado ao work item ${args.id} (anexos atuais: ${attachedNames(before).length}).`);
console.log(`[dry-run] enviaria POST ${projUrl}/_apis/wit/attachments?fileName=${encodeURIComponent(fileName)} (${content.length} bytes) e PATCH ${wiUrl} com rel=AttachedFile.`);
return;
}
// 1. Upload do arquivo bruto (devolve a url do attachment).
const up = await call('POST', `${projUrl}/_apis/wit/attachments?fileName=${encodeURIComponent(fileName)}&api-version=7.1-preview.3`,
token, content, 'application/octet-stream');
// 2. Vincula a url ao work item.
const patch = [{ op: 'add', path: '/relations/-', value: { rel: 'AttachedFile', url: up.url, attributes: { comment: 'Anexo ' + fileName } } }];
await call('PATCH', `${wiUrl}?api-version=7.1`, token, Buffer.from(JSON.stringify(patch), 'utf8'), 'application/json-patch+json');
// 3. Confirma.
const after = await call('GET', `${wiUrl}?$expand=relations&api-version=7.1`, token);
if (!attachedNames(after).includes(fileName)) fail(`upload feito (${up.url}), mas o vínculo não aparece no work item ${args.id}.`);
console.log(`OK: ${fileName} anexado ao work item ${args.id}.`);
}
// Erro de uso (parâmetro obrigatório ausente) sai com 2, junto com o uso; os demais, com 1.
main().catch((e) => {
console.error('ERRO: ' + (e instanceof Fail ? e.message : (e && e.stack) || e));
if (e instanceof UsageFail) console.error(USAGE);
process.exitCode = e instanceof UsageFail ? 2 : 1;
});