maestri-remote/.context/skills/git-devops-productivity/scripts/outlier-commits.mjs

84 lines
3.5 KiB
JavaScript

#!/usr/bin/env node
// Lista os commits de um autor que mais somam linhas adicionadas numa janela, para achar o outlier
// antes de aceitar um número de produtividade (SKILL.md, checklist, passo 6).
//
// Substitui o laço em bash `git log … | while read …; git show --numstat … | grep -vE … | awk …; done
// | sort -rn | head`, que só rodava em bash. Só lê o repositório: `git log` e `git show`.
//
// Uso:
// node .context/skills/git-devops-productivity/scripts/outlier-commits.mjs <repo> --since "<janela>" --author "<email>" [--top 10]
//
// Saída (stdout): uma linha por commit, "<linhas-adicionadas>\t<hash>\t<data>\t<assunto>", do maior para
// o menor, limitada a --top (padrão 10).
//
// Exclusão: só o filtro leve do laço original (graphify-out/, knowledge_base.json, package-lock), de
// propósito: o objetivo aqui é ENXERGAR o que infla o número. A contagem oficial, com a lista completa de
// exclusões, é a do count-loc.mjs. Arquivo binário (numstat "-") conta 0.
// Só módulos nativos do Node 18+.
import { spawnSync } from 'node:child_process';
const EXCLUIR = /graphify-out\/|knowledge_base\.json$|package-lock/;
const USO = 'uso: node outlier-commits.mjs <repo> --since "<janela>" --author "<email>" [--top 10]';
function uso(msg) {
if (msg) console.error(`erro: ${msg}`);
console.error(USO);
process.exitCode = 2;
}
function git(args) {
const r = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
if (r.error) throw r.error;
if (r.status !== 0) throw new Error(`git ${args.join(' ')} falhou: ${(r.stderr || '').trim()}`);
return r.stdout;
}
function main() {
const args = process.argv.slice(2);
// --help/-h: uso no stdout e código 0, antes de validar qualquer parâmetro.
if (args.some((a) => a === '--help' || a === '-h')) { console.log(USO); return; }
let repo = null;
let since = null;
let author = null;
let top = 10;
for (let i = 0; i < args.length; i++) {
const a = args[i];
const valor = () => (i + 1 < args.length ? args[++i] : null);
if (a === '--since') since = valor();
else if (a === '--author') author = valor();
else if (a === '--top') top = Number(valor());
else if (a.startsWith('--')) return uso(`opção desconhecida ${a}`);
else if (repo === null) repo = a;
else return uso(`argumento a mais: ${a}`);
}
if (!repo || !since || !author) return uso('informe <repo>, --since e --author');
if (!Number.isInteger(top) || top <= 0) return uso('--top espera um inteiro maior que zero');
const log = git(['-C', repo, 'log', '--all', `--since=${since}`, '--no-merges', `--author=${author}`,
'--format=%H%x09%ad%x09%s', '--date=short']);
const linhas = [];
for (const linha of log.split('\n')) {
if (!linha) continue;
const [hash, data, ...resto] = linha.split('\t');
let soma = 0;
for (const n of git(['-C', repo, 'show', '--numstat', '--format=', hash]).split('\n')) {
const partes = n.split('\t');
if (partes.length !== 3 || EXCLUIR.test(partes[2])) continue;
soma += Number(partes[0]) || 0;
}
linhas.push({ soma, hash, data, assunto: resto.join('\t') });
}
linhas.sort((a, b) => b.soma - a.soma);
for (const l of linhas.slice(0, top)) console.log(`${l.soma}\t${l.hash}\t${l.data}\t${l.assunto}`);
if (linhas.length === 0) console.error('(nenhum commit desse autor na janela; confira o --author contra `git shortlog -sne --all`)');
}
try {
main();
} catch (e) {
console.error(`erro: ${e.message}`);
process.exitCode = 1;
}