/
amesk
/
gitlab-analyzer
Обзор
Документация
Войти
/
amesk
/
gitlab-analyzer
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
jquery
gitlab.js
167 строк
6 KB
amesk
Removed redundant logging.
15 фев 2025, 14:43
15 фев 2025, 14:43
320fa3a
Код
Авторство
О чём код?
// gitlab.js const { Gitlab } = require('@gitbeaker/node'); // Конфигурация GitLab const GITLAB_URL = 'http://gitlab.evomarine.local'; const ACCESS_TOKEN = ''; // Инициализация клиента GitLab api = new Gitlab({ host: GITLAB_URL, token: ACCESS_TOKEN, }); function setupApiToken(token) { api = new Gitlab({ host: GITLAB_URL, token: token, }); } /** * Обновляет метку у задачи в GitLab * @param {string} projectId - ID проекта * @param {number} issueId - ID задачи * @param {string} label - Метка * @param {string} action - Действие (add или remove) * @returns {Promise<{success: boolean, error?: string}>} */ async function updateLabel(projectId, issueId, label, action) { try { // Получаем текущие метки задачи const issue = await api.Issues.show(projectId, issueId); const currentLabels = issue.labels; // Обновляем метки let newLabels; if (action === 'add') { if (!currentLabels.includes(label)) { newLabels = [...currentLabels, label]; } else { return { success: true }; // Метка уже существует, ничего не делаем } } else if (action === 'remove') { if (currentLabels.includes(label)) { newLabels = currentLabels.filter(l => l !== label); } else { return { success: true }; // Метки нет, ничего не делаем } } else { return { success: false, error: 'Invalid action' }; } // Обновляем задачу с новыми метками await api.Issues.edit(projectId, issueId, { labels: newLabels.join(','), }); return { success: true }; } catch (error) { console.error('Error updating label:', error); return { success: false, error: error.message }; } } async function getProjectLabels(projectId) { try { const labels = await api.Labels.all(projectId); return { success: true, labels: labels.map(label => ({name: label.name, color: label.color})) }; } catch (error) { console.error('Error fetching open issues:', error); return { success: false, error: error.message }; } } /** * Получает список открытых задач для проекта * @param {string} projectId - ID проекта * @returns {Promise<{success: boolean, issues?: Array, error?: string}>} */ async function getOpenIssues(projectId) { try { // Получаем список открытых задач const issues = await api.Issues.all({ projectId, state: 'opened', }); // Получаем метки проекта const labels = await api.Labels.all(projectId); const labelColors = labels.reduce((acc, label) => { acc[label.name] = label.color; return acc; }, {}); // Формируем список задач с метками, assignee, milestone, estimation и spent time const issuesList = await Promise.all(issues.map(async (issue) => { // Получаем информацию о времени (estimation и spent time) const timeStats = await api.Issues.timeStats(projectId, issue.iid); const createdAt = new Date(issue.created_at); const updatedAt = new Date(issue.updated_at); // Дата последнего обновления const now = new Date(); const ageInSeconds = Math.floor((now - createdAt) / 1000); const lastUpdatedInSeconds = Math.floor((now - updatedAt) / 1000); const priority = issue.labels.reduce((max, item) => { if (!isNaN(item)) { const currentNumber = parseInt(item, 10); if (currentNumber > max) { return currentNumber; } } return max; }, 0); return { iid: issue.iid, title: issue.title, url: issue.web_url, labels: issue.labels.map(label => [label, labelColors[label] || "#CCCCCC"]), priority: priority, assignee: issue.assignee ? issue.assignee.name : null, // Добавляем assignee milestone: issue.milestone ? issue.milestone.title : null, // Добавляем milestone estimation: timeStats.time_estimate, // Оценка времени total_time_spent: timeStats.total_time_spent, // Суммарное время, списанное на пункт age: ageInSeconds, updated: lastUpdatedInSeconds }; })); return { success: true, issues: issuesList }; } catch (error) { console.error('Error fetching open issues:', error); return { success: false, error: error.message }; } } /** * Закрывает выбранные задачи в GitLab * @param {string} projectId - ID проекта * @param {Array<number>} issueIds - Массив ID задач * @returns {Promise<{success: boolean, error?: string}>} */ async function closeIssues(projectId, issueIds) { try { // Закрываем каждую задачу for (const issueId of issueIds) { await api.Issues.edit(projectId, issueId, { state_event: 'close', }); } return { success: true }; } catch (error) { console.error('Error closing issues:', error); return { success: false, error: error.message }; } } module.exports = { setupApiToken, updateLabel, getProjectLabels, getOpenIssues, closeIssues, GITLAB_URL };