ÿØÿà JFIF    ÿÛ „  ( %!1"%)+...383-7(-.+  -%%--------+------------/----------------------------ÿÀ  ¶" ÿÄ     ÿÄ @    !1AQaq‘¡"±ÁÑð2’BRráS‚ñ3b¢CT²Ò #cÿÄ    ÿÄ '   1!AQ2a"‘±#ÿÚ   ? ò(/p‘—–¢·,M|¯G»R£üešT. ôŸEoCFñ‡ 4ÔkåóxR|µÁ¨ÓDà!Ç´µ˜‡p ÍQ‹§!þž^õWsŒy  åÁ§$á«%ºq˜™JyyË0y«^Ϗ -3ÃÏËÈ£Æ\P’ä„s&•‹Üs üô'àWt¹pñCp$bÚF`·7.^)¾!)ÒÙ˜–ÅÏš^h¾ø³·ìe±ŒaeÖ—Í,e=B}Jéߦ$$½—šÙÜCC¯¶è8β–Åkèwx LÉngT±æ¹£Ócœ¿Í/©Éÿ ‰ÚCÒ­mq;Tt¶–}0"zÖPcd1š­¤tˆ„ÐÓâqú[™öUCŠ2޿د­É(¸ßúçšmW,Ò ºf‹Ån™ÄLêÁ8üÁkÁ€L¥ÍuJ1œôrÂSŒÓöt!7EUíïb)AËi¬â-ÙHk8òÁiXYwÅ)O^"ÇØriÛô{»wRUKÙÏÚlÓ¬€‚’שT ] ªb—ÊîKC^×M“xùäñz¬zJ× {4[¹M'IÆeH1LCWÕ]œûº WDæà°OÅ‚¹c²ÞuA–rL`HšpCez‡V’— Ž‚Ë„–ñ­'µR0ÕÖ=À:±G»C\nÆÉ5*¢ †3šhQ4ýÒi$Õ1"Ü]¢p-q3zcQ$ªö¨¥æf›‘»´ÝÚHá„e²JÇ–iÊ:·à¬Øc5Åk»Laª*wi [0Ówk ¦a¦0Õ²ÅÅ‚T¸’³q:Æ<¹ú Ò˜Æ}2VE•Ѐp¡Ô3Úº …h³^LJºçì¥Ánó|˜ÖˆÎˆ+« ¦dø‘Mº–d\ªDðÛ„Ì×LÝ——Ð9Ç|•FèçVm™¨€™3õS–9Äå¢<̉Ìm¢±`·º˜&Z²ž Ë®D«¶»6™‰©­HÈ Àá«h­i³04æ’hxœi3ï¨(ÓL·†‹¶ËpŒ ƒÜÒ? :õdsÀ –3æÓ·Üjâ¬9—]8n¼&]I F£¼…ì–—Œ0v°LǐÅfÛ2TÖ’aµ˜N@ÖBSÏ^à´4-±°b×nÈÈœÆD=KdŒø…ÄÈK,›ÖR§fjü$^ÔÎ!„6^ s:Üun\ôkCÞò÷<—Lúl Í›G¹ÀPá¼Nc¡šÒ…ÙWͳœ±vÊáЄ×9‹P‰cEØ‘™›µŸP<×g1 º©Ø¬wiÁ^l5× I/';Ë+´Z‡ÓÄFÕp[Èð’ HÄ ó 9¬Dl4“é±Ï”V=^Hð;žLädÉa‚°Ë,#/Ž~²BÔÛ QãñQtIeórVB,ÏÂf‹4#Μc‹É3ZIÖ Œ¢¥·üxa‡Ãçè„jŠ[5 Ä!U?,3žÎ×…ðdÓ÷háŠA‰ìÄ4÷ÃÜZÃE{‰®+W\ZÍE[‰»µk»MÝ­`¢©†˜ÃV‹-f¢¡†¢a«eŠ%«Y¨©q%jâd,Ôq`) ¤¦…šˆ ¦E>0Ùb²t–Ÿ  ÷jsςҒKÈcø(é›;k(’#ôŒQ ™C> õ³M9óºÆµ¤çâ;uÀ)5>RÔ¸fÓ~Ȧ—’-$fe«"FâUˆÊwµPÏu w+"åÉó¨6s™Û9(À¨ù©hE°½†n`m~“@©›p!Vkhµ Á1šbEqqÊ@ºèl›2 –Yã%‘‚hÛ{a¶‡ÅÞM²¬çL34®Çl]®‹ŽØŒm'RÜe35æöˆ­Á­ cP9šeÁköo´L³Ì=p8]”‡B¶,šº|ɏdzXˆØk*ÇÚ{#ñ‰pã(€¶‡9ý'šÜ³½¯kƒ†Â’ëSOƒ•Å®H6+a¢µˆ‹Y¨b˜b+XˆÖ!°u!¢"µˆˆn2ˆ Å0Ä`Å Ô®c(ÓÜGº•Ä»Œ âWî%q.áÐÄ÷î%umÍ£+ÜQ,Vn¦-GphU¸¢X­&,Gt ·K¢ÅÅ·¥RÄÊÉbKn N­R2g$VµÕó Qr#–ÓZUÏð0ÎtÙÀœz ëöo“Îk¯n„T°"SÞ+³/…€½"ižãO%Í%&Δâ‘ËØ´IˆÓ°Ë‰ÞM3.™yçÁzit›`4C`k¢¼á!álÄï sÂ[×!¤l¾æo"ƒIÔ'@ªu)3›ô®“@Z à¾] üœ'‡4¸PÞkÁ-qÄH‰ÓÍBd´ÿ —¹°ÄA&ÊUC„öz‚‚RæŠtf¬>˜ÑidšEçÑL÷áý¡V±h§­c¿¥¨ƒ@g¼…Ýö^ÞËc.ž„æ“I[ ª+·zÐÒÚ,½Ð»¶€C›7jk$๖€Ž¾ÅÙpp¶ÍþéΤ ½ØÎŒq ñpæžÅ¥#Øâ49ÃÂK^MYV“,¶Éz_òæ:…;Õ«¦I3âJ£¤û5$7Èxün\â]Êe¯(Ÿ&Ž‹¶2<6Ćf× æ¢ƱqWı[(ÙÂŽç‚T7¨@ÈÉÍß‚ïÙ"&3TYlGށ†)†#5ŠA©^T2ÆÁ†)©†©†¤yGXÁ†©"†)©¼ÅV WS†#©]R–r‹q5ÕbâWþBh¯u+ªÅÄ×ü„nÑ^êkªÁj‰jeœWˆÕÕ`µDµ2Ì+Ä µDµµ5Ô{¤Þ0RF’H÷AÛ<ÊÁ§ ƈæ0Ñ£ê4 öÚµ[¬/1²€â<-¬šö²r×0o×w ´xÐÒË„ g01¬„åEM蛇Ã\6µE›‘fÙO k÷CºnÓ1`iîÒ² áÂ!ÑLÄÿ ³¬\õ*:M=Ç»c‹2[‰ØsÕLò\ŒK L^™üÄN\¶#» Ç\……ßïIœÉ$¸ÎñÍ®ÔHÇ Ûí/´>Li”„†g^$ 7NÍÑÑ2M2ªNg=k½Ð}Ÿl6‡ —JWˆ”ÞéT·+µ¦üÂFè¢Vs6ýÆ4»2+2IÝ9ô9®ÇGÙÇ1+Ä8;*Õ§ž½D*îÑWÚçá3Ma¤·ˆ¥t}š²Ü…Q+Æüµ8HíS”üxGéÁˆ¦Ël„éÈ 5 µÄƒ6äÜ(kIš¯S†fÖ&¸®×v|Äyˆ*禌Éù@7-®Ä[]ÎÖ¿ê`º…=:…žJVnݳvðÖKE¼‚ »mà ÷f®:Ë ™–4rð¡4` ܹçž~‹C=œ…¾Ïj|VDtK.ƒ"9 Ï ­–éXá³6WÒïIL-Ї Ç src/create.mjs000064400000005341152266407770007334 0ustar00#!/usr/bin/env node // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import inquirer from 'inquirer'; import chalk from 'chalk'; import { createNote } from './note.mjs'; import { getInitialValues } from './helpers.mjs'; import * as Prompts from './prompts.mjs'; import logger from './logger.mjs'; export default async (options) => { // Processs the initial values. const initialValues = getInitialValues(options); // Fetch information. const messages = []; const { issueNumber } = await inquirer.prompt([ Prompts.getIssuePrompt(), ], initialValues); let selection = {}; let notePath; do { selection = {}; selection = await inquirer.prompt([ Prompts.getComponentsPrompt(), Prompts.getTypePrompt(), Prompts.getMessagePromptInput(), ], initialValues); if (selection.message === '') { selection = Object.assign( selection, await inquirer.prompt([ Prompts.getMessagePromptEditor(), ]), ); } logger.info(` Creating upgrade note with the following options: - Issue: ${chalk.bold(issueNumber)} - Component: ${chalk.bold(selection.components)} - Type: ${chalk.bold(selection.type)} - Message: ${chalk.bold(selection.message)} `); messages.push({ components: [selection.components], type: selection.type, message: selection.message, }); // Save the note so far. if (notePath) { await createNote(issueNumber, messages, notePath); logger.info(`Updated note at: ${chalk.underline(chalk.bold(notePath))}`); } else { notePath = await createNote(issueNumber, messages); logger.info(`Note created at: ${chalk.underline(chalk.bold(notePath))}`); } selection = Object.assign( selection, await inquirer.prompt([ Prompts.getAddAnotherPrompt(), ], initialValues), ); } while (selection.addAnother); }; src/note.mjs000064400000013703152266407770007037 0ustar00// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import yaml from 'js-yaml'; import path from 'path'; import { writeFile, mkdir, readdir, readFile, unlink } from 'fs/promises'; import { isValidNoteName, sortNoteTypes } from './noteTypes.mjs'; import { sortComponents } from './components.mjs'; const unreleasedPath = path.resolve('.upgradenotes'); /** * Get the filename for the note. * * @param {string} issueNumnber The issue number * @returns {string} */ const getFilename = (issueNumber) => { const dateTimeFormat = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', fractionalSecondDigits: 2, timeZone: 'UTC', }); const date = Object.fromEntries( dateTimeFormat.formatToParts(new Date()) .filter((p) => p.type !== 'literal') .map((p) => ([p.type, p.value])) ); const dateString = [ date.year, date.month, date.day, date.hour, date.minute, date.second, date.fractionalSecond, ].join(''); return `${issueNumber}-${dateString}.yml`; }; /** * Create a new note. * * @param {string} issueNumber * @param {[type: string]: {message: string}} messages * @returns {string} The path to the note on disk */ export const createNote = async ( issueNumber, messages, notePath, ) => { const note = { issueNumber, notes: {}, }; messages.forEach(({components, type, message}) => { note.notes[components] = note.notes[components] || []; note.notes[components].push({message, type}); }); if (!notePath) { notePath = path.resolve(unreleasedPath, getFilename(issueNumber)); } const noteContent = yaml.dump(note); await mkdir(unreleasedPath, {recursive: true}); await writeFile(notePath, noteContent); return notePath; }; /** * Get all unreleased notes. * * @returns {Promise<{issueNumber: string, components: string[], types: {[type: string]: {message: string}[]}}[]> */ export const getAllNotes = async () => { const files = await readdir(unreleasedPath); const notes = files .filter((file) => file.endsWith('.yml')) .map(async (file) => { const filePath = path.resolve(unreleasedPath, file); const fileContent = await readFile(filePath, 'utf8'); return { ...yaml.load(fileContent), filePath, }; }); return Promise.all(notes); }; /** * Get the list of notes, grouped by note type, then component. * * @returns {Promise<{[type: string]: {[components: string]: {message: string, issueNumber: string}[]}}>} */ export const getCombinedNotes = async () => { const notes = await getAllNotes(); const combinedNotes = {}; notes.forEach((note) => { Object.entries(note.notes).forEach(([components, data]) => { data.forEach((entry) => { if (!isValidNoteName(entry.type)) { throw new Error(`Invalid note type: "${entry.type}" in file ${note.filePath}`); } combinedNotes[entry.type] = combinedNotes[entry.type] || {}; combinedNotes[entry.type][components] = combinedNotes[entry.type][components] || []; combinedNotes[entry.type][components].push({message: entry.message, issueNumber: note.issueNumber}); }); }); }); return combinedNotes; }; /** * Get the list of notes, grouped by component, then by note type. * * @returns {Promise<{[component: string]: {[type: string]: {message: string, issueNumber: string}[]}}>} */ export const getCombinedNotesByComponent = async () => { const notes = await getAllNotes(); const combinedNotes = {}; notes.forEach((note) => { Object.entries(note.notes).forEach(([component, data]) => { combinedNotes[component] = combinedNotes[component] || {}; data.forEach((entry) => { if (!isValidNoteName(entry.type)) { throw new Error(`Invalid note type: "${entry.type}" in file ${note.filePath}`); } combinedNotes[component][entry.type] = combinedNotes[component][entry.type] || []; combinedNotes[component][entry.type].push({ component, message: entry.message, issueNumber: note.issueNumber, type: entry.type, }); }); }); }); // Sort notes by note type. Object.entries(combinedNotes).forEach(([component, types]) => { combinedNotes[component] = Object.fromEntries( Object.entries(types).sort(([a], [b]) => sortNoteTypes(a, b)) ); }); // Sort components. return Object.fromEntries( Object.entries(combinedNotes).sort(([a], [b]) => sortComponents(a, b)) ); }; /** * Delete all unreleased notes. * * @returns {Promise} */ export const deleteAllNotes = async () => { const files = await readdir(unreleasedPath); return Promise.all( files .filter((item, index) => files.indexOf(item) === index) .filter((file) => file.endsWith('.yml')) .map((file) => unlink(`${unreleasedPath}/${file}`)) ); }; src/generate.mjs000064400000026024152266407770007664 0ustar00#!/usr/bin/env node // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import chalk from 'chalk'; import { getAllComponents } from './components.mjs'; import { getCombinedNotesByComponent, deleteAllNotes } from './note.mjs'; import { getNoteName } from './noteTypes.mjs'; import { writeFile, readFile, unlink } from 'fs/promises'; import { join as joinPath } from 'path'; import logger from './logger.mjs'; import { getCurrentVersion } from './helpers.mjs'; /** * Helper to fetch the current notes from a file. * * @param {string} file * @returns {Promise} */ const getCurrentNotes = async (file) => { try { return await readFile(file, 'utf8'); } catch (error) { return null; } } /** * Update the UPGRADING.md file. * * @param {string} upgradeNotes * @param {Object} options * @param {boolean} options.deleteNotes * @returns {Promise} */ const updateUpgradeNotes = async (upgradeNotes, options) => { const fileName = 'UPGRADING.md'; // Write the notes to a file. logger.info(`Writing notes to ${chalk.underline(chalk.bold(fileName))}`); // Prepend to the existing file. const existingContent = await getCurrentNotes(fileName); if (existingContent) { await writeFile(fileName, getUpdatedNotes(existingContent, upgradeNotes)); } else { // This should not normally happen. await writeFile(fileName, upgradeNotes); } if (options.deleteNotes) { logger.warn(`>>> Deleting all notes <<<`) // Delete the notes. deleteAllNotes(); } }; /** * Create the current summary notes. * * @param {string} upgradeNotes * @returns {Promise} */ const createCurrentSummary = async (upgradeNotes) => { const fileName = 'UPGRADING-CURRENT.md'; const notes = `# Moodle upgrade notes\n\n${upgradeNotes}`; await writeFile(fileName, notes); logger.info(`Running upgrade notes written to ${chalk.underline(chalk.bold(fileName))}`); }; /** * Get the indexes of the lines that contain the version headings. * * @param {array} lines * @returns {array} */ const getVersionLineIndexes = (lines) => { const h2Indexes = []; lines.forEach((line, index) => { const matches = line.match(/^##\s(?.*)$/); if (matches) { h2Indexes.push({ index, line, version: matches.groups.version, }); } }); return h2Indexes; }; /** * Find the index of the Unreleased heading. * * @param {array} versionHeadings * @returns {number} */ const findUnreleasedHeadingIndex = (versionHeadings) => versionHeadings.findIndex((heading) => { if (heading.version === 'Unreleased') { // Used if version cannot be guessed. return true; } if (heading.version.endsWith('+')) { // Weekly release for a stable branch. return true; } if (heading.version.match(/beta|rc\d/)) { // Beta and RC rolls are treated as weeklies. return true; } if (heading.version.endsWith('dev')) { // Development version. return true; } return false; }); /** * Get the before and after content, to facilitate replacing any existing Unreleased notes. * * @param {array} lines * @returns {Object} {beforeContent: string, afterContent: string} */ const getBeforeAndAfterContent = (lines) => { const existingLines = lines.split('\n'); const versionHeadings = getVersionLineIndexes(existingLines); if (versionHeadings.length > 0) { const unreleasedHeadingIndex = findUnreleasedHeadingIndex(versionHeadings); if (unreleasedHeadingIndex !== -1) { const beforeContent = existingLines.slice(0, versionHeadings[unreleasedHeadingIndex].index).join('\n'); if (versionHeadings.length > unreleasedHeadingIndex + 1) { const afterContent = existingLines.slice(versionHeadings[unreleasedHeadingIndex + 1].index).join('\n'); return { beforeContent, afterContent, }; } return { beforeContent, afterContent: '', }; } return { beforeContent: existingLines.slice(0, versionHeadings[0].index).join('\n'), afterContent: existingLines.slice(versionHeadings[0].index).join('\n'), }; } return { beforeContent: existingLines.join('\n'), afterContent: '', } }; /** * Get the notes for the component. * * @param {string} types * @param {Number} headingLevel * @returns {string} */ const getNotesForComponent = (types, headingLevel) => { let upgradeNotes = ''; Object.entries(types).forEach(([type, notes]) => { upgradeNotes += '#'.repeat(headingLevel); upgradeNotes += ` ${getNoteName(type)}\n\n`; notes.forEach(({ message, issueNumber }) => { // Split the message into lines, removing empty lines. const messageLines = message .split('\n') // Remove empty lines between tables, and list entries, but not after lists. .filter((line, index, lines) => { if (line.trim().length === 0) { // This line is empty. // If it's the first line in the file, remove it. if (index === 0) { return false; } // This is the last line in the file, remove it. if (index === lines.length - 1) { return false; } // If the previous line relates to a table, remove this line. if (lines[index - 1].match(/^\s*\|/)) { return false; } // If the next line is also empty, do not remove this line. if (lines[index + 1].trim().length === 0) { return true; } // Do not remove the line if the previous line was a list item. if (lines[index - 1].match(/^\s*[-*]\s/)) { return true; } if (lines[index - 1].match(/^\s*\d+\.\s/)) { return true; } // Preserve all other empty lines by default. return true; } // Keep any line which has content. return true; }); const firstLine = messageLines.shift().trim(); upgradeNotes += `- ${firstLine}\n`; messageLines .forEach((line) => { upgradeNotes += ` ${line}`.trimEnd() + `\n`; }); upgradeNotes += `\n For more information see [${issueNumber}](https://tracker.moodle.org/browse/${issueNumber})\n`; }); upgradeNotes += '\n'; }); return upgradeNotes; }; /** * Get the updated notes mixed with existing content. * * @param {string} existingContent * @param {string} upgradeNotes */ const getUpdatedNotes = (existingContent, upgradeNotes) => { const { beforeContent, afterContent } = getBeforeAndAfterContent(existingContent); const newContent = `${beforeContent}\n${upgradeNotes}\n${afterContent}` .split('\n') .filter((line, index, lines) => { if (line === '' && lines[index - 1] === '') { // Remove multiple consecutive empty lines. return false; } return true; }) .join('\n'); return newContent; }; /** * Update the notes for each component. */ const updateComponentNotes = ( notes, version, notesFileName = 'UPGRADING.md', removeEmpty = false, ) => { return getAllComponents().map(async (component) => { logger.verbose(`Updating notes for ${component.name} into ${component.path}`); const fileName = joinPath(component.path, notesFileName); const existingContent = await getCurrentNotes(fileName); if (!existingContent) { if (!notes[component.value]) { // No existing notes, and no new notes to add. return; } } else { if (!notes[component.value]) { // There is existing content, but nothing to add. if (removeEmpty) { logger.verbose(`Removing empty notes file ${fileName}`); await unlink(fileName); } return; } } const componentNotes = notes[component.value]; let upgradeNotes = `## ${version}\n\n`; upgradeNotes += getNotesForComponent(componentNotes, 3); if (existingContent) { await writeFile(fileName, getUpdatedNotes(existingContent, upgradeNotes)); } else { await writeFile( fileName, `# ${component.name} Upgrade notes\n\n${upgradeNotes}`, ); } }); } /** * Generate the upgrade notes for a new release. * * @param {string|undefined} version * @param {Object} options * @param {boolean} options.generateUpgradeNotes * @param {boolean} options.deleteNotes * @returns {Promise} */ export default async (version, options = {}) => { const notes = await getCombinedNotesByComponent(); if (Object.keys(notes).length === 0) { logger.warn('No notes to generate'); return; } if (!version) { version = await getCurrentVersion(); } // Generate the upgrade notes for this release. // We have // - a title with the release name // - the change types // - which contain the components // - which document each change let upgradeNotes = `## ${version}\n\n`; Object.entries(notes).forEach(([component, types]) => { upgradeNotes += `### ${component}\n\n`; upgradeNotes += getNotesForComponent(types, 4); }); await Promise.all([ createCurrentSummary(upgradeNotes), ...updateComponentNotes(notes, version, 'UPGRADING-CURRENT.md', true), ]); if (options.generateUpgradeNotes) { await Promise.all(updateComponentNotes(notes, version)); await updateUpgradeNotes(upgradeNotes, options); } }; src/helpers.mjs000064400000013425152266407770007535 0ustar00// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import chalk from 'chalk'; import { isStandardComponent, isCommunityComponent, rewritePlugintypeAsSubsystem } from './components.mjs'; import { isValidNoteName } from './noteTypes.mjs'; import logger from './logger.mjs'; import { readFile } from 'fs/promises'; /** * Validate an issue number input * * @param {string} input * @returns {string|boolean} */ export const validateIssueNumber = (input) => { if (!input) { return 'You must provide a tracker issue number'; } if (input.match(/^[a-zA-Z]*-\d+$/)) { return true; } if (input.match(/^\d+$/)) { return true; } return 'The issue number was not recognised as a valid issue number'; }; /** * Format an issue number input. * * @param {string} input * @returns {string} */ export const formatIssueNumber = (input) => { if (input.match(/^[a-zA-Z]*-\d+$/)) { return input; } if (input.match(/^\d+$/)) { return `MDL-${input}`; } return input; }; /** * Validate a component. * * @param {string} input * @returns {string|boolean} */ export const validateComponent = (input) => { if (isStandardComponent(input)) { return true; } if (isCommunityComponent(input)) { return 'Currently only core plugins are supported.'; } return 'The component was not recognised as a standard component'; }; export const formatComponent = (input) => { if (rewritePlugintypeAsSubsystem(input)) { return `core_${input}`; } return input; } /** * Get the initial values from the options. * * @param {object} options * @returns {object} */ export const getInitialValues = (options) => { const initialValues = {}; const type = getInitialTypeValue(options); if (type) { initialValues.type = type; } const issueNumber = getInitialIssueValue(options); if (issueNumber) { initialValues.issueNumber = issueNumber; } const component = getInitialComponentValue(options); if (component) { initialValues.components = component; } const message = getInitialMessageValue(options); if (message) { initialValues.message = message initialValues.addAnother = false; } return initialValues; }; /** * Get the initial type value. * * @param {Object} options * @returns {string|undefined} */ const getInitialTypeValue = (options) => { if (!options.type) { return; } options.type = options.type.trim().toLowerCase(); if (isValidNoteName(options.type)) { return options.type; } logger.warn(`Note type "${chalk.underline(chalk.red(options.type))}" is not valid.`); }; /** * Get the initial issue number value. * * @param {Object} options * @returns {string|undefined} */ const getInitialIssueValue = (options) => { if (!options.issue) { return; } options.issue = options.issue.trim().toUpperCase(); const issueNumberValidated = validateIssueNumber(options.issue); if (issueNumberValidated === true) { const issueNumber = formatIssueNumber(options.issue); if (issueNumber !== options.issue) { logger.warn( `Issue number "${chalk.underline(chalk.red(options.issue))}" was updated to ` + `"${chalk.underline(chalk.green(issueNumber))}"` ); } return issueNumber; } else { logger.warn(`Issue number "${chalk.underline(chalk.red(options.issue))}" is not valid: ${issueNumberValidated}`); } }; /** * Get the initial component value. * * @param {Object} options * @returns {string|undefined} */ const getInitialComponentValue = (options) => { if (!options.component) { return; } options.component = options.component.trim().toLowerCase(); const componentValidated = validateComponent(options.component); if (componentValidated === true) { const component = formatComponent(options.component); if (component !== options.component) { logger.warn( `Component "${chalk.underline(chalk.red(options.component))}" was updated to ` + `"${chalk.underline(chalk.green(component))}"` ); } return component; } else { logger.warn(`Component "${chalk.underline(chalk.red(options.component))}" is not valid: ${componentValidated}`); } }; /** * Get the initial message value. * * @param {Object} options * @returns {string|undefined} */ const getInitialMessageValue = (options) => { if (!options.message) { return; } return options.message.trim(); }; /** * Get the current version from the project /version.php file. * * @returns {Promise} */ export const getCurrentVersion = async () => { const versionRegex = new RegExp(/^ *\$release *= *['\"](?[^ \+]+\+?) *\(Build:.*/m); try { const versionFile = await readFile('version.php', 'utf8'); const match = versionFile.match(versionRegex); if (match) { return match.groups.release; } } catch(error) { logger.error('Unable to read the version file'); } return "Unreleased"; } src/components.mjs000064400000007515152266407770010263 0ustar00// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import * as Components from '../../components.js'; const componentData = Components.fetchComponentData(); /** * The standard components shipped with core Moodle. * * @type {Object} */ export const standardComponents = componentData.standardComponents; /** * All components of the current Moodle instance. * * @type {Object} */ export const allComponents = componentData.components; /** * Get all components of the current Moodle instance. * * @returns {Array} */ export const getAllComponents = () => { let components = new Map(Object.entries(componentData.pluginTypes).map(([value, path]) => ([path,{ path, value, name: `${value} (plugin type)`, }]))); Object .entries(componentData.components) .filter(([path, value]) => Object.values(componentData.standardComponents).includes(value)) .forEach(([path, value]) => { const entry = { path, value, name: value, }; if (Object.values(componentData.subsystems).includes(value)) { if (components.has(path)) { entry.name = `${value} (subsystem / plugintype)`; } else { entry.name = `${value} (subsystem)`; } } components.set(path, entry); }); return Array.from(components.values()); }; /** * Whether the specified component is a standard component shipped with core Moodle. * * @param {string} componentName * @returns {boolean} */ export const isStandardComponent = (componentName) => { if (Object.values(componentData.standardComponents).includes(componentName)) { return true; } if (Object.keys(componentData.pluginTypes).includes(componentName)) { return true; } return false; }; export const rewritePlugintypeAsSubsystem = (componentName) => { if (Object.keys(componentData.pluginTypes).includes(componentName)) { const pluginTypePath = componentData.pluginTypes[componentName]; if (Object.keys(componentData.subsystems).includes(pluginTypePath)) { return true; } } return false; }; /** * Whether the specified component is a community component. * * @param {string} componentName * @returns {boolean} */ export const isCommunityComponent = (componentName) => { if (isStandardComponent(componentName)) { return false; } return Object.values(componentData.components).indexOf(componentName) !== -1; }; /** * Sort method for components. * * This method sorts components putting `core` first, followed by core subsystems, then everything else. * * @param {String} a * @param {String} b * @returns {Number} */ export const sortComponents = (a, b) => { // Always put 'core' first. if (a === 'core') { return -1; } else if (b === 'core') { return 1; } // Put core subsystems next. if (a.startsWith('core_') && !b.startsWith('core_')) { return -1; } else if (b.startsWith('core_') && !a.startsWith('core_')) { return 1; } // Sort alphabetically for everything else. return a.localeCompare(b); }; src/noteTypes.mjs000064400000003556152266407770010071 0ustar00// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . /** * The note types. * * Matches the suggested order in https://keepachangelog.com/en/1.1.0/. * @type {Object} */ const noteTypes = { 'improved': 'Added', 'changed': 'Changed', 'deprecated': 'Deprecated', 'removed': 'Removed', 'fixed': 'Fixed', }; /** * The preferred order of note types. * * @type {string[]} */ const preferredOrder = Object.keys(noteTypes); /** * Comparison method to sort note types. * * @param {String} a * @param {String} b * @returns {Number} */ export const sortNoteTypes = (a, b) => { const aIndex = preferredOrder.indexOf(a); const bIndex = preferredOrder.indexOf(b); if (aIndex === -1) { return 1; } if (bIndex === -1) { return -1; } return aIndex - bIndex; }; /** * Get the note names. * * @returns {string[]} */ export const getNoteNames = () => Object.keys(noteTypes); /** * Get the human-readable note name. * * @param {string} type * @returns {string} */ export const getNoteName = (type) => noteTypes[type]; /** * Whether the note name is valid. * * @param {string} type * @returns {boolean} */ export const isValidNoteName = (type) => noteTypes[type] !== undefined; src/logger.mjs000064400000001746152266407770007355 0ustar00#!/usr/bin/env node // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import winston from 'winston'; const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.colorize(), winston.format.simple() ), transports: [ new winston.transports.Console(), ], }); export default logger; src/prompts.mjs000064400000007557152266407770007610 0ustar00// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . import inquirer from 'inquirer'; import SearchList from 'inquirer-search-list'; import { getNoteNames } from './noteTypes.mjs'; import { getAllComponents } from './components.mjs'; import { formatComponent, formatIssueNumber, validateComponent, validateIssueNumber, } from './helpers.mjs'; /** * A Search List which accepts an initial value. */ class SearchListWithInitialValue extends SearchList { constructor(options, ...args) { super(options, ...args); if (options.default) { const pointer = this.filterList.findIndex((item) => { return item.value === options.default; }); if (pointer > -1) { this.pointer = pointer; } } } } inquirer.registerPrompt('search-list', SearchListWithInitialValue); /** * Get the issue type prompt. * * @param {string} defaultData The initially selected value * @returns {Object} */ export const getTypePrompt = (defaultData) => ({ default: defaultData, type: 'search-list', message: 'Type of change', name: 'type', choices: getNoteNames(), validate: (selection) => { if (selection.length < 1) { return 'You must select at least one type of change'; } return true; }, }); /** * Get the component prompt. * * @param {string} [defaultValue='core'] The initally selected value. * @returns */ export const getComponentsPrompt = (defaultValue) => { if (!defaultValue ) { defaultValue = 'core'; } return { choices: getAllComponents(), default: defaultValue, type: 'search-list', message: 'Component', name: 'components', validate: validateComponent, filter: formatComponent, }; }; /** * Get the issue number prompt as an inline input. * * @param {string} defaultData * @returns {object} */ export const getIssuePrompt = (defaultData) => ({ default: defaultData, type: 'input', message: 'Tracker issue number', name: 'issueNumber', validate: validateIssueNumber, filter: formatIssueNumber, }); /** * Get a message prompt. * * @param {string} defaultData * @returns */ export const getMessagePromptEditor = (defaultData) => ({ default: defaultData, type: process.stdin.isTTY ? 'editor' : 'input', postfix: '.md', message: 'Message', name: 'message', waitUserInput: false, validate: (input) => { if (!input) { return 'You must provide a message'; } return true; }, // Remove any trailing whitespace. filter: (input) => input.split('\n').map((line) => line.trimEnd()).join('\n'), }); /** * Get a message prompt. * * @param {string} defaultData * @returns */ export const getMessagePromptInput = (defaultData) => ({ default: defaultData, type: 'input', message: 'Message (leave empty to use editor)', name: 'message', filter: (input) => input.trim(), }); /** * Get a prompt to ask the user if they wish to add another entry. * * @returns {Object} */ export const getAddAnotherPrompt = () => ({ type: 'confirm', message: 'Do you want to add another note?', default: false, name: 'addAnother', });