JavaScript Python PHP
function executar(values) {
function productivityText(value, label = 'Campo') {
if (value === undefined)
return '';
if (typeof value !== 'string' || value.length > 100000)
throw new Error(label + ': informe texto de até 100 mil unidades UTF-16.');
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\uD800-\uDFFF]/u.test(value))
throw new Error(label + ': caracteres de controle ou Unicode inválido.');
return value.replace(/\r\n?/g, '\n');
}
function productivityOutput(output) {
if (output.text.length > 1000000)
throw new Error('Saída excede 1 milhão de unidades UTF-16.');
return output;
}
function generateCommitChangelog(v) {
const mode = productivityChoice(v.mode, ['Mensagem de commit', 'Changelog']);
if (mode === 'Mensagem de commit') {
const type = productivityChoice(v.type, ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert']);
const scope = productivityLabel(v.scope, 'Escopo', true), description = productivityLabel(v.description, 'Descrição');
if (scope && !/^[A-Za-z0-9_./-]+$/.test(scope))
throw new Error('Escopo: use letras ASCII, dígitos, _, ., / ou -.');
const breaking = productivityChoice(v.breaking, ['Não', 'Sim']) === 'Sim', body = productivityText(v.body, 'Corpo').trim();
const detail = breaking ? productivityLabel(v.breakingDescription, 'Descrição da quebra') : '';
return { text: type + (scope ? '(' + scope + ')' : '') + (breaking ? '!' : '') + ': ' + description + (body ? '\n\n' + body : '') + (breaking ? '\n\nBREAKING CHANGE: ' + detail : ''), filename: 'COMMIT_MESSAGE.txt' };
}
const source = productivityChoice(v.source, ['Conventional Commits', 'Mudanças livres']), version = productivityLabel(v.version, 'Versão'), date = productivityDate(v.date);
const lines = productivityLines(v.input, 'Commits/mudanças', true), groups = new Map();
for (const line of lines) {
let title = 'Mudanças', content = line;
if (source === 'Conventional Commits') {
const match = /^([A-Za-z][A-Za-z0-9-]*)(?:\(([A-Za-z0-9_./-]+)\))?(!)?: (.+)$/.exec(line);
if (!match)
throw new Error('Cabeçalho de commit inválido: ' + line + '. Use um cabeçalho por linha; sinalize quebras com !. Corpos e footers não são aceitos nesta entrada.');
const type = match[1].toLowerCase(), titles = { feat: 'Novidades', fix: 'Correções', docs: 'Documentação', perf: 'Desempenho', refactor: 'Refatoração', test: 'Testes' };
title = match[3] ? 'Mudanças incompatíveis' : Object.hasOwn(titles, type) ? titles[type] : 'Outras mudanças';
content = (match[2] ? '(' + match[2] + ') ' : '') + match[4];
}
if (!groups.has(title))
groups.set(title, []);
groups.get(title).push(content);
}
let text = '# Changelog\n\n## ' + productivityMd(version) + (date ? ' — ' + date : '') + '\n';
for (const [title, changes] of groups)
text += '\n### ' + title + '\n\n' + changes.map(line => '- ' + productivityMd(line)).join('\n') + '\n';
return { text, filename: 'CHANGELOG.md' };
}
function text(value, label) {
if (typeof value !== 'string')
throw new Error(label + ': informe texto.');
if (value.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
return value;
}
function productivityLabel(value, label, optional = false) {
const content = productivityText(value, label).trim();
if ((!content && !optional) || content.length > 200 || /[\n\t\u2028\u2029]/.test(content))
throw new Error(label + ': use uma linha de 1–200 caracteres' + (optional ? ' ou deixe vazio.' : '.'));
return content;
}
function productivityChoice(value, options) {
if (typeof value !== 'string' || !options.includes(value))
throw new Error('Escolha uma opção válida: ' + options.join(', ') + '.');
return value;
}
function productivityMd(value) {
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/[\\`*_{}[\]()#+.!|~-]/g, '\\$&');
}
function productivityLines(value, label, required = false) {
const lines = productivityText(value, label).split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length > 500 || required && !lines.length)
throw new Error(label + ': informe de ' + (required ? '1' : '0') + ' a 500 linhas não vazias.');
return lines;
}
function productivityDate(value) {
const date = productivityLabel(value, 'Data', true);
if (!date)
return '';
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || date.startsWith('0000') || !Number.isFinite(Date.parse(date + 'T00:00:00Z')) || new Date(date + 'T00:00:00Z').toISOString().slice(0, 10) !== date)
throw new Error('Data inválida: use YYYY-MM-DD e um dia real do calendário.');
return date;
}
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateCommitChangelog(values));
}
import re
import datetime
def executar(values):
def text(value='', label='Campo'):
if not isinstance(value,str) or len(value.encode('utf-16-le',errors='surrogatepass'))//2 > 100000: raise ValueError(label+': informe texto de até 100 mil unidades UTF-16.')
if re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]',value): raise ValueError(label+': controles ou Unicode inválido.')
return value.replace('\r\n','\n').replace('\r','\n')
def trim(value):
return value.strip('\t\n\r \v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')
def label(value, title, optional=False):
content=trim(text(value,title))
if (not content and not optional) or len(content.encode('utf-16-le'))//2>200 or re.search(r'[\n\t\u2028\u2029]',content): raise ValueError(title+': use uma linha de 1–200 caracteres.')
return content
def choice(value, options):
if value not in options: raise ValueError('Escolha uma opção válida.')
return value
def md(value):
value=value.replace('&','&').replace('<','<').replace('>','>')
return re.sub(r'[\\`*_{}[\]()#+.!|~-]',lambda m:'\\'+m[0],value)
def lines(value, title, required=False):
result=[trim(line) for line in text(value,title).split('\n') if trim(line)]
if len(result)>500 or required and not result: raise ValueError(title+': informe até 500 linhas não vazias.')
return result
def date(value=''):
content=label(value,'Data',True)
if not content: return ''
if not re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}',content): raise ValueError('Data inválida: use YYYY-MM-DD.')
datetime.date.fromisoformat(content)
return content
def finish(content, filename):
if len(content.encode('utf-16-le'))//2>1000000: raise ValueError('Saída excede 1 milhão de unidades UTF-16.')
return {'text':content,'filename':filename}
for value in values.values(): text(value)
mode=choice(values.get('mode'),['Mensagem de commit','Changelog'])
if mode=='Mensagem de commit':
kind=choice(values.get('type'),['feat','fix','docs','style','refactor','perf','test','build','ci','chore','revert'])
scope=label(values.get('scope',''),'Escopo',True); description=label(values.get('description',''),'Descrição')
if scope and not re.fullmatch(r'[A-Za-z0-9_./-]+',scope): raise ValueError('Escopo inválido.')
breaking=choice(values.get('breaking'),['Não','Sim'])=='Sim'; body=trim(text(values.get('body',''),'Corpo'))
detail=label(values.get('breakingDescription',''),'Descrição da quebra') if breaking else ''
return finish(kind+('('+scope+')' if scope else '')+('!' if breaking else '')+': '+description+('\n\n'+body if body else '')+('\n\nBREAKING CHANGE: '+detail if breaking else ''),'COMMIT_MESSAGE.txt')
source=choice(values.get('source'),['Conventional Commits','Mudanças livres']); version=label(values.get('version',''),'Versão'); when=date(values.get('date','')); groups={}
for line in lines(values.get('input',''),'Commits/mudanças',True):
title='Mudanças'; content=line
if source=='Conventional Commits':
match=re.fullmatch(r'([A-Za-z][A-Za-z0-9-]*)(?:\(([A-Za-z0-9_./-]+)\))?(!)?: (.+)',line)
if not match: raise ValueError('Cabeçalho de commit inválido; use um cabeçalho por linha.')
kind=match[1].lower(); titles={'feat':'Novidades','fix':'Correções','docs':'Documentação','perf':'Desempenho','refactor':'Refatoração','test':'Testes'}
title='Mudanças incompatíveis' if match[3] else titles.get(kind,'Outras mudanças'); content=('('+match[2]+') ' if match[2] else '')+match[4]
groups.setdefault(title,[]).append(content)
out='# Changelog\n\n## '+md(version)+(' — '+when if when else '')+'\n'
for title,changes in groups.items(): out+='\n### '+title+'\n\n'+'\n'.join('- '+md(item) for item in changes)+'\n'
return finish(out,'CHANGELOG.md')
<?php
function executar(array $values): array {
$text = function ($value = '', $label = 'Campo') {
if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto de até 100 mil unidades UTF-16.');
if (preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $value)) throw new InvalidArgumentException($label.': caracteres de controle.');
return str_replace(["\r\n","\r"],"\n",$value);
};
$trimText = fn($value)=>preg_replace('/^[\s\x{FEFF}]+|[\s\x{FEFF}]+$/u','',$value);
$label = function ($value,$title,$optional=false) use ($text,$trimText) {
$content=$trimText($text($value,$title));
if (($content==='' && !$optional) || strlen(iconv('UTF-8','UTF-16LE',$content))/2>200 || preg_match('/[\n\t\x{2028}\x{2029}]/u',$content)) throw new InvalidArgumentException($title.': use uma linha de 1–200 caracteres.');
return $content;
};
$choice = function ($value,$options) {
if (!in_array($value,$options,true)) throw new InvalidArgumentException('Escolha uma opção válida.');
return $value;
};
$md = function ($value) {
$value=str_replace(['&','<','>'],['&','<','>'],$value);
return preg_replace_callback('/[\\\\`*_{}\[\]()#+.!|~\-]/',fn($m)=>'\\'.$m[0],$value);
};
$lines = function ($value,$title,$required=false) use ($text,$trimText) {
$result=array_values(array_filter(array_map($trimText,explode("\n",$text($value,$title))),fn($x)=>$x!==''));
if (count($result)>500 || ($required && !$result)) throw new InvalidArgumentException($title.': informe até 500 linhas não vazias.');
return $result;
};
$date = function ($value='') use ($label) {
$content=$label($value,'Data',true); if ($content==='') return '';
if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D',$content) || !checkdate((int)substr($content,5,2),(int)substr($content,8,2),(int)substr($content,0,4))) throw new InvalidArgumentException('Data inválida: use YYYY-MM-DD e um dia real.');
return $content;
};
$finish = function ($content,$filename) {
if (strlen(iconv('UTF-8','UTF-16LE',$content))/2>1000000) throw new InvalidArgumentException('Saída excede 1 milhão de unidades UTF-16.');
return ['text'=>$content,'filename'=>$filename];
};
foreach ($values as $value) $text($value);
$mode=$choice($values['mode'],['Mensagem de commit','Changelog']);
if ($mode==='Mensagem de commit') {
$type=$choice($values['type'],['feat','fix','docs','style','refactor','perf','test','build','ci','chore','revert']); $scope=$label($values['scope'] ?? '','Escopo',true); $description=$label($values['description'] ?? '','Descrição');
if ($scope!=='' && !preg_match('/^[A-Za-z0-9_.\/-]+$/D',$scope)) throw new InvalidArgumentException('Escopo inválido.');
$breaking=$choice($values['breaking'],['Não','Sim'])==='Sim'; $body=$trimText($text($values['body'] ?? '','Corpo')); $detail=$breaking ? $label($values['breakingDescription'] ?? '','Descrição da quebra') : '';
return $finish($type.($scope!=='' ? '('.$scope.')' : '').($breaking ? '!' : '').': '.$description.($body!=='' ? "\n\n".$body : '').($breaking ? "\n\nBREAKING CHANGE: ".$detail : ''),'COMMIT_MESSAGE.txt');
}
$source=$choice($values['source'],['Conventional Commits','Mudanças livres']); $version=$label($values['version'] ?? '','Versão'); $when=$date($values['date'] ?? ''); $groups=[];
foreach ($lines($values['input'] ?? '','Commits/mudanças',true) as $line) {
$title='Mudanças'; $content=$line;
if ($source==='Conventional Commits') {
if (!preg_match('/^([A-Za-z][A-Za-z0-9-]*)(?:\(([A-Za-z0-9_.\/-]+)\))?(!)?: (.+)$/D',$line,$match)) throw new InvalidArgumentException('Cabeçalho de commit inválido; use um cabeçalho por linha.');
$type=strtolower($match[1]); $titles=['feat'=>'Novidades','fix'=>'Correções','docs'=>'Documentação','perf'=>'Desempenho','refactor'=>'Refatoração','test'=>'Testes'];
$title=!empty($match[3]) ? 'Mudanças incompatíveis' : ($titles[$type] ?? 'Outras mudanças'); $content=(!empty($match[2]) ? '('.$match[2].') ' : '').$match[4];
}
$groups[$title][]=$content;
}
$out="# Changelog\n\n## ".$md($version).($when!=='' ? ' — '.$when : '')."\n";
foreach ($groups as $title=>$changes) $out.="\n### ".$title."\n\n".implode("\n",array_map(fn($x)=>'- '.$md($x),$changes))."\n";
return $finish($out,'CHANGELOG.md');
}