From f13b1f6416c999dfebc7d759e5d60b34c972ba8c Mon Sep 17 00:00:00 2001 From: Vitaly <53114367+Nukeap@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:00:21 +0300 Subject: [PATCH] =?UTF-8?q?chore=20[P-0]:=20=D1=81hore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 0 src/front/changelog.config.cjs | 276 +++++++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+) create mode 100644 CHANGELOG.md create mode 100755 src/front/changelog.config.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..e69de29b diff --git a/src/front/changelog.config.cjs b/src/front/changelog.config.cjs new file mode 100755 index 00000000..b520ae1f --- /dev/null +++ b/src/front/changelog.config.cjs @@ -0,0 +1,276 @@ +const axios = require('axios') +const Handlebars = require('handlebars') + +// НАСТРОЙКИ ПОДКЛЮЧЕНИЯ К ВАШЕМУ YOUTRACK +const YOUTRACK_URL = 'https://project.9966hub.ru' +const YOUTRACK_TOKEN = 'perm:TnVrZWFw.NTItMQ==.nUhvPQJnPmsmaEex597VM4bvHFTtLm' + +const ticketSummaryCache = new Map() +// Глобальная структура для группировки: тип -> раздел -> задачи +const globalGroupedData = new Map() +// Храним последний коммит для каждого типа +const lastCommitPerType = new Map() + +function getrepolink(context) { + return context.packageData.repository.url.replace(/\.git$/, '') +} +// Асинхронный запрос к YouTrack API за названием и тегами задачи +async function fetchYouTrackData(issueId) { + if (ticketSummaryCache.has(issueId)) { + return ticketSummaryCache.get(issueId) + } + + try { + const response = await axios.get(`${YOUTRACK_URL}/api/issues/${issueId}`, { + params: { + fields: + 'summary,tags(name,color(background,foreground)),customFields(projectCustomField(field(name)),value(name))', + }, + paramsSerializer: { + serialize: (params) => `fields=${params.fields}`, + }, + headers: { + Authorization: `Bearer ${YOUTRACK_TOKEN}`, + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + timeout: 3000, + }) + + const summary = response.data.summary || 'Задача без названия' + const issue = response.data + const customFields = issue && issue.customFields ? issue.customFields : [] + + const sectionField = customFields.find( + (cf) => + cf.projectCustomField && + cf.projectCustomField.field && + cf.projectCustomField.field.name === 'Раздел', + ) + let sectionValue = 'Общее' + if (sectionField && sectionField.value) { + sectionValue = sectionField.value.name + } + + let tagsString = '' + const tagsArray = response.data.tags || [] + const excludedTags = ['feat', 'fix', 'perf', 'docs', 'style', 'refactor', 'test', 'chore'] + if (tagsArray.length > 0) { + tagsString = tagsArray + .filter( + (tag) => + tag && tag.name && tag.name && !excludedTags.includes(tag.name.trim().toLowerCase()), + ) + .map((tag) => { + return `  ${tag.name.trim()}` + }) + .join('') + } + + const data = { summary, tags: tagsString, subgroup: sectionValue } + ticketSummaryCache.set(issueId, data) + return data + } catch (error) { + console.error(`\n⚠️ Не удалось загрузить данные из YouTrack для ${issueId}: ${error.message}`) + return null + } +} +Handlebars.registerHelper('formatDate', function (dateString) { + if (!dateString) return '' + const date = new Date(dateString) + if (Number.isNaN(date.getTime())) return dateString + + const day = String(date.getDate()).padStart(2, '0') + const month = String(date.getMonth() + 1).padStart(2, '0') + const year = date.getFullYear() + + return `${day}.${month}.${year}` +}) +// Регистрируем хелперы для работы с глобальной структурой +Handlebars.registerHelper('getSubgroups', function (type) { + if (!globalGroupedData.has(type)) return [] + const typeMap = globalGroupedData.get(type) + return Array.from(typeMap.keys()).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) +}) + +Handlebars.registerHelper('getTasksBySubgroup', function (type, subgroup) { + if (!globalGroupedData.has(type)) return [] + const typeMap = globalGroupedData.get(type) + if (!typeMap.has(subgroup)) return [] + return typeMap.get(subgroup) +}) + +async function collectCommitData(commit, context) { + if (!commit.scope || !commit.scope.startsWith('UKD-')) { + return + } + const ticketNumber = Number.parseInt(commit.scope.replace('UKD-', ''), 10) + + if (Number.isNaN(ticketNumber) || ticketNumber <= 213) { + return + } + const repourl = getrepolink(context) + const issueId = commit.scope.trim() + const youTrackData = await fetchYouTrackData(issueId) + + const officialTitle = youTrackData ? youTrackData.summary : 'Задача без названия в трекере' + const ticketTags = youTrackData && youTrackData.tags ? youTrackData.tags : '' + const ticketgroup = youTrackData && youTrackData.subgroup ? youTrackData.subgroup : 'Общее' + const currentSubject = commit.subject ? commit.subject.trim() : '' + const currentHash = typeof commit.hash === 'string' ? commit.hash.substring(0, 7) : 'no-hash' + + let author = 'Неизвестен' + if (currentHash !== 'no-hash') { + try { + const { execSync } = require('child_process') + author = execSync(`git log -n 1 ${currentHash} --format="%an"`).toString().trim() + } catch (e) { + author = commit.authorName || commit.committerName || 'Неизвестен' + } + } + + const bodyLine = commit.body ? `${commit.body.trim()}` : '' + const commitLine = `
  • ${currentSubject} (${currentHash}) @${author}${bodyLine}
  • ` + + // Определяем отображаемый тип + let displayType = commit.type + if (displayType === 'feat') displayType = `🚀 Новые возможности (${commit.type})` + else if (displayType === 'fix') displayType = `🐛 Исправления ошибок (${commit.type})` + else if (displayType === 'perf') displayType = `⚡ Оптимизация и скорость (${commit.type})` + else if (displayType === 'docs') displayType = `📝 Документация (${commit.type})` + else if (displayType === 'style') displayType = `🎨 Стили и оформление (${commit.type})` + else if (displayType === 'refactor') displayType = `♻️ Рефакторинг кода (${commit.type})` + else if (displayType === 'test') displayType = `✅ Тестирование (${commit.type})` + else if (displayType === 'chore') displayType = `🔧 Технические задачи (${commit.type})` + else return + + // Собираем данные в глобальную структуру + if (!globalGroupedData.has(displayType)) { + globalGroupedData.set(displayType, new Map()) + } + + const typeMap = globalGroupedData.get(displayType) + if (!typeMap.has(ticketgroup)) { + typeMap.set(ticketgroup, []) + } + + const tasks = typeMap.get(ticketgroup) + + // Ищем задачу с таким же scope + let existingTask = tasks.find((t) => t.scope === commit.scope) + if (existingTask) { + existingTask.historyLines.push(commitLine) + } else { + tasks.push({ + scope: commit.scope, + youtrackUrl: YOUTRACK_URL, + officialTitle: officialTitle, + ticketTags: ticketTags, + historyLines: [commitLine], + }) + } + + // Сохраняем последний коммит для этого типа + const clonedCommit = { ...commit } + clonedCommit.type = displayType + clonedCommit._displayType = displayType + clonedCommit.ticketgroup = ticketgroup + lastCommitPerType.set(displayType, clonedCommit) +} + +module.exports = new Promise((resolve) => { + resolve({ + parserOpts: { + headerPattern: + /^(feat|fix|perf|docs|style|refactor|test|chore)\s*\[\s*(UKD-\d+)\s*\]\s*:\s*(.*)$/, + headerCorrespondence: ['type', 'scope', 'subject'], + noteKeywords: ['BREAKING CHANGE'], + }, + + writerOpts: { + transform: async (commit, context) => { + await collectCommitData(commit, context) + // Groups are rendered through isDummy commits added by finalizeContext. + return null + }, + + finalizeContext: (context) => { + console.error('DEBUG version =', JSON.stringify(context.version)) + console.error('DEBUG date =', JSON.stringify(context.date)) + console.error('DEBUG tag =', JSON.stringify(context.currentTag)) + const commitGroups = context.commitGroups || [] + const groupedMap = new Map() + + commitGroups.forEach((group) => { + groupedMap.set(group.title, group) + }) + + for (const [type, commit] of lastCommitPerType) { + if (!groupedMap.has(type)) { + const dummyCommit = { + ...commit, + isDummy: true, + hash: 'dummy', + subject: '', + type: type, + _displayType: type, + } + + const newGroup = { + title: type, + commits: [dummyCommit], + } + commitGroups.push(newGroup) + } + } + + context.commitGroups = commitGroups + return context + }, + + groupBy: 'type', + commitGroupsSort: 'title', + commitsSort: ['scope'], + + // ОБНОВЛЕННЫЙ commitPartial - все задачи как выпадающие списки + commitPartial: + ` +{{#if isDummy}} +{{#each (getSubgroups _displayType)}} +#### {{this}} + +{{#each (getTasksBySubgroup ../_displayType this)}} +
    +{{scope}}: {{officialTitle}}{{{ticketTags}}} + +
    +{{/each}} + +{{/each}} +{{/if}} +`.trim() + '\n', + + // mainTemplate + mainTemplate: ` +{{#if version}} + +## 📦 Версия {{version}} ({{formatDate date}}) +---------------------------------- +{{/if}} + +{{#each commitGroups}} +### {{title}} + +{{#each commits}} +{{> commit}} +{{/each}} + +{{/each}} +`, + }, + }) +})