freeCodeCamp/curriculum/getChallenges.js

432 lines
14 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
const path = require('path');
const util = require('util');
const assert = require('assert');
const yaml = require('js-yaml');
const { findIndex, isEmpty } = require('lodash');
const readDirP = require('readdirp');
const { helpCategoryMap } = require('../client/utils/challenge-types');
const { showUpcomingChanges } = require('../config/env.json');
const { curriculum: curriculumLangs } =
2022-10-26 17:08:27 +00:00
require('../config/i18n').availableLangs;
2021-02-01 18:31:39 +00:00
const { parseMD } = require('../tools/challenge-parser/parser');
/* eslint-disable max-len */
const {
translateCommentsInChallenge
2021-02-03 09:46:27 +00:00
} = require('../tools/challenge-parser/translation-parser');
/* eslint-enable max-len*/
const { isAuditedCert } = require('../utils/is-audited');
const { createPoly } = require('../utils/polyvinyl');
const { dasherize } = require('../utils/slugs');
const { getSuperOrder, getSuperBlockFromDir } = require('./utils');
const access = util.promisify(fs.access);
const CHALLENGES_DIR = path.resolve(__dirname, 'challenges');
const META_DIR = path.resolve(CHALLENGES_DIR, '_meta');
exports.CHALLENGES_DIR = CHALLENGES_DIR;
exports.META_DIR = META_DIR;
2020-09-28 13:16:30 +00:00
const COMMENT_TRANSLATIONS = createCommentMap(
path.resolve(__dirname, 'dictionaries')
2020-09-28 13:16:30 +00:00
);
function getTranslatableComments(dictionariesDir) {
const COMMENTS_TO_TRANSLATE = require(path.resolve(
dictionariesDir,
'english',
'comments.json'
));
return Object.values(COMMENTS_TO_TRANSLATE);
}
exports.getTranslatableComments = getTranslatableComments;
2020-09-28 13:16:30 +00:00
function createCommentMap(dictionariesDir) {
// get all the languages for which there are dictionaries.
const languages = fs
.readdirSync(dictionariesDir)
.filter(x => x !== 'english');
// get all their dictionaries
const dictionaries = languages.reduce(
(acc, lang) => ({
...acc,
[lang]: require(path.resolve(dictionariesDir, lang, 'comments.json'))
2020-09-28 13:16:30 +00:00
}),
{}
);
// get the english dicts
const COMMENTS_TO_TRANSLATE = require(path.resolve(
dictionariesDir,
'english',
'comments.json'
));
const COMMENTS_TO_NOT_TRANSLATE = require(path.resolve(
dictionariesDir,
'english',
'comments-to-not-translate'
));
2020-09-28 13:16:30 +00:00
// map from english comment text to translations
const translatedCommentMap = Object.entries(COMMENTS_TO_TRANSLATE).reduce(
(acc, [id, text]) => {
2020-09-28 13:16:30 +00:00
return {
...acc,
[text]: getTranslationEntry(dictionaries, { engId: id, text })
};
},
{}
);
// map from english comment text to itself
const untranslatableCommentMap = Object.values(
COMMENTS_TO_NOT_TRANSLATE
).reduce((acc, text) => {
const englishEntry = languages.reduce(
(acc, lang) => ({
2020-09-28 13:16:30 +00:00
...acc,
[lang]: text
}),
{}
);
return {
...acc,
[text]: englishEntry
};
}, {});
2020-09-28 13:16:30 +00:00
return { ...translatedCommentMap, ...untranslatableCommentMap };
}
exports.createCommentMap = createCommentMap;
function getTranslationEntry(dicts, { engId, text }) {
return Object.keys(dicts).reduce((acc, lang) => {
const entry = dicts[lang][engId];
2020-09-28 13:16:30 +00:00
if (entry) {
return { ...acc, [lang]: entry };
2020-09-28 13:16:30 +00:00
} else {
// default to english
return { ...acc, [lang]: text };
2020-09-28 13:16:30 +00:00
}
}, {});
}
function getChallengesDirForLang(lang) {
return path.resolve(CHALLENGES_DIR, `${lang}`);
}
function getMetaForBlock(block) {
return JSON.parse(
fs.readFileSync(path.resolve(META_DIR, `${block}/meta.json`), 'utf8')
);
}
function parseCert(filePath) {
return yaml.load(fs.readFileSync(filePath, 'utf8'));
}
exports.getChallengesDirForLang = getChallengesDirForLang;
exports.getMetaForBlock = getMetaForBlock;
// This recursively walks the directories starting at root, and calls cb for
// each file/directory and only resolves once all the callbacks do.
const walk = (root, target, options, cb) => {
return new Promise(resolve => {
let running = 1;
function done() {
if (--running === 0) {
resolve(target);
}
}
readDirP(root, options)
.on('data', file => {
running++;
cb(file, target).then(done);
})
.on('end', done);
});
};
exports.getChallengesForLang = async function getChallengesForLang(lang) {
// english determines the shape of the curriculum, all other languages mirror
// it.
const root = getChallengesDirForLang('english');
// scaffold the curriculum, first set up the superblocks, then recurse into
// the blocks
const curriculum = await walk(
root,
{},
{ type: 'directories', depth: 0 },
buildSuperBlocks
);
Object.entries(curriculum).forEach(([name, superBlock]) => {
assert(!isEmpty(superBlock.blocks), `superblock ${name} has no blocks`);
});
const cb = (file, curriculum) => buildChallenges(file, curriculum, lang);
// fill the scaffold with the challenges
return walk(
root,
curriculum,
{ type: 'files', fileFilter: ['*.md', '*.yml'] },
cb
);
};
async function buildBlocks({ basename: blockName }, curriculum, superBlock) {
const metaPath = path.resolve(META_DIR, `${blockName}/meta.json`);
if (fs.existsSync(metaPath)) {
// try to read the file, if the meta path does not exist it should be a certification.
// As they do not have meta files.
const blockMeta = JSON.parse(fs.readFileSync(metaPath));
const { isUpcomingChange } = blockMeta;
if (typeof isUpcomingChange !== 'boolean') {
throw Error(
`meta file at ${metaPath} is missing 'isUpcomingChange', it must be 'true' or 'false'`
);
}
if (!isUpcomingChange || showUpcomingChanges) {
// add the block to the superBlock
const blockInfo = { meta: blockMeta, challenges: [] };
curriculum[superBlock].blocks[blockName] = blockInfo;
}
} else {
curriculum['certifications'].blocks[blockName] = { challenges: [] };
}
}
2018-11-16 18:22:52 +00:00
async function buildSuperBlocks({ path, fullPath }, curriculum) {
const superBlock = getSuperBlockFromDir(getBaseDir(path));
curriculum[superBlock] = { blocks: {} };
const cb = (file, curriculum) => buildBlocks(file, curriculum, superBlock);
return walk(fullPath, curriculum, { depth: 1, type: 'directories' }, cb);
}
async function buildChallenges({ path: filePath }, curriculum, lang) {
// path is relative to getChallengesDirForLang(lang)
const block = getBlockNameFromPath(filePath);
const superBlockDir = getBaseDir(filePath);
const superBlock = getSuperBlockFromDir(superBlockDir);
2018-10-10 20:20:40 +00:00
let challengeBlock;
// TODO: this try block and process exit can all go once errors terminate the
// tests correctly.
2018-10-10 20:20:40 +00:00
try {
challengeBlock = curriculum[superBlock].blocks[block];
if (!challengeBlock) {
// this should only happen when a isUpcomingChange block is skipped
return;
}
2018-10-10 20:20:40 +00:00
} catch (e) {
console.log(`failed to create superBlock from ${superBlockDir}`);
2018-10-25 09:54:57 +00:00
// eslint-disable-next-line no-process-exit
process.exit(1);
2018-10-10 20:20:40 +00:00
}
const { meta } = challengeBlock;
const isCert = path.extname(filePath) === '.yml';
feat: enable new curriculum (#44183) * feat: use legacy flag chore: reorder challenges fix: linter revert: server change feat: unblock new editor fix: proper order fix: 0-based order fix: broke the order feat: move tribute certification to its own block feat: split the old projects block into 4 fix: put all blocks in order chore: add intro text refactor: use block, not blockName in query fix: project progress indicator * fix: reorder new challenges/certs * fix: reorder legacy challenges * fix: reintroduce legacy certs * feat: add showNewCurriculum flag to env * chore: forgot sample.env * feat: use feature flag for display * fix: rename meta + dirs to match new blocks * fix: add new blocks to help-category-map * fix: update completion-modal for new GQL schema * test: duplicate title/id errors -> warnings * fix: update completion-modal to new GQL schema Mk2 * chore: re-order metas (again) * fix: revert super-block-intro changes The intro needs to show both legacy and new content. We need to decide which pages are created, rather than than what a page shows when rendered. * feat: move upcoming curriculum into own superblock * fix: handle one certification with two superBlocks * fix: remove duplicated intros * fix: remove duplicate projects from /settings * fix: drop 'two' from Responsive Web Design Two * chore: rename slug suffix from two to v2 * feat: control display of new curriculum * feat: control project paths shown on /settings * fix: use new project order for /settings This does mean that /settings will change before the release, but I don't think it's serious. All the projects are there, just not in the legacy order. * fix: claim/show cert button * chore: remove isLegacy Since we have legacy superblocks, we don't currently need individual blocks to be legacy * test: fix utils.test * fix: verifyCanClaim needs certification If Shaun removes the cert claim cards, maybe we can remove this entirely * fix: add hasEditableBoundaries flags where needed * chore: remove isUpcomingChange * chore: v2 -> 22 Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2021-12-20 18:36:31 +00:00
// TODO: there's probably a better way, but this makes sure we don't build any
// of the new curriculum when we don't want it.
if (
!showUpcomingChanges &&
meta?.superBlock === '2022/javascript-algorithms-and-data-structures'
) {
return;
}
const createChallenge = generateChallengeCreator(CHALLENGES_DIR, lang);
const challenge = isCert
? await createCertification(CHALLENGES_DIR, filePath, lang)
: await createChallenge(filePath, meta);
2018-11-16 18:22:52 +00:00
challengeBlock.challenges = [...challengeBlock.challenges, challenge];
}
async function parseTranslation(transPath, dict, lang, parse = parseMD) {
const translatedChal = await parse(transPath);
const { challengeType } = translatedChal;
// challengeType 11 is for video challenges and 3 is for front-end projects
// neither of which have seeds.
return challengeType !== 11 && challengeType !== 3
? translateCommentsInChallenge(translatedChal, lang, dict)
: translatedChal;
}
async function createCertification(basePath, filePath) {
function getFullPath(pathLang) {
return path.resolve(__dirname, basePath, pathLang, filePath);
}
// TODO: restart using isAudited() once we can determine a) the superBlocks
// (plural) a certification belongs to and b) get that info from the parsed
// certification, rather than the path. ASSUMING that this is used by the
// client. If not, delete this comment and the lang param.
return parseCert(getFullPath('english'));
}
// This is a slightly weird abstraction, but it lets us define helper functions
// without passing around a ton of arguments.
function generateChallengeCreator(basePath, lang) {
function getFullPath(pathLang, filePath) {
2020-12-17 14:02:56 +00:00
return path.resolve(__dirname, basePath, pathLang, filePath);
}
async function validate(filePath, superBlock) {
const invalidLang = !curriculumLangs.includes(lang);
if (invalidLang)
throw Error(`${lang} is not a accepted language.
Trying to parse ${filePath}`);
const missingEnglish =
lang !== 'english' && !(await hasEnglishSource(basePath, filePath));
if (missingEnglish)
throw Error(`Missing English challenge for
${filePath}
It should be in
${getFullPath('english', filePath)}
`);
const missingAuditedChallenge =
isAuditedCert(lang, superBlock) &&
!fs.existsSync(getFullPath(lang, filePath));
if (missingAuditedChallenge)
throw Error(`Missing ${lang} audited challenge for
${filePath}
Explanation:
Challenges that have been already audited cannot fall back to their English versions. If you are seeing this, please update, and approve these Challenges on Crowdin first, followed by downloading them to the main branch using the GitHub workflows.
`);
}
function addMetaToChallenge(challenge, meta) {
const challengeOrder = findIndex(
meta.challengeOrder,
([id]) => id === challenge.id
);
challenge.block = meta.name ? dasherize(meta.name) : null;
challenge.hasEditableBoundaries = !!meta.hasEditableBoundaries;
challenge.order = meta.order;
// const superOrder = getSuperOrder(meta.superBlock);
2022-04-25 18:00:27 +00:00
// NOTE: Use this version when a super block is in beta.
const superOrder = getSuperOrder(meta.superBlock, {
// switch this back to SHOW_NEW_CURRICULUM when we're ready to beta the JS superblock
showNewCurriculum: process.env.SHOW_UPCOMING_CHANGES === 'true'
});
if (superOrder !== null) challenge.superOrder = superOrder;
/* Since there can be more than one way to complete a certification (using the
feat: enable new curriculum (#44183) * feat: use legacy flag chore: reorder challenges fix: linter revert: server change feat: unblock new editor fix: proper order fix: 0-based order fix: broke the order feat: move tribute certification to its own block feat: split the old projects block into 4 fix: put all blocks in order chore: add intro text refactor: use block, not blockName in query fix: project progress indicator * fix: reorder new challenges/certs * fix: reorder legacy challenges * fix: reintroduce legacy certs * feat: add showNewCurriculum flag to env * chore: forgot sample.env * feat: use feature flag for display * fix: rename meta + dirs to match new blocks * fix: add new blocks to help-category-map * fix: update completion-modal for new GQL schema * test: duplicate title/id errors -> warnings * fix: update completion-modal to new GQL schema Mk2 * chore: re-order metas (again) * fix: revert super-block-intro changes The intro needs to show both legacy and new content. We need to decide which pages are created, rather than than what a page shows when rendered. * feat: move upcoming curriculum into own superblock * fix: handle one certification with two superBlocks * fix: remove duplicated intros * fix: remove duplicate projects from /settings * fix: drop 'two' from Responsive Web Design Two * chore: rename slug suffix from two to v2 * feat: control display of new curriculum * feat: control project paths shown on /settings * fix: use new project order for /settings This does mean that /settings will change before the release, but I don't think it's serious. All the projects are there, just not in the legacy order. * fix: claim/show cert button * chore: remove isLegacy Since we have legacy superblocks, we don't currently need individual blocks to be legacy * test: fix utils.test * fix: verifyCanClaim needs certification If Shaun removes the cert claim cards, maybe we can remove this entirely * fix: add hasEditableBoundaries flags where needed * chore: remove isUpcomingChange * chore: v2 -> 22 Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2021-12-20 18:36:31 +00:00
legacy curriculum or the new one, for instance), we need a certification
field to track which certification this belongs to. */
const dupeCertifications = [
{
certification: 'responsive-web-design',
dupe: '2022/responsive-web-design'
},
{
certification: 'javascript-algorithms-and-data-structures',
dupe: '2022/javascript-algorithms-and-data-structures'
}
];
const hasDupe = dupeCertifications.find(
cert => cert.dupe === meta.superBlock
);
challenge.certification = hasDupe ? hasDupe.certification : meta.superBlock;
challenge.superBlock = meta.superBlock;
challenge.challengeOrder = challengeOrder;
challenge.isPrivate = challenge.isPrivate || meta.isPrivate;
challenge.required = (meta.required || []).concat(challenge.required || []);
challenge.template = meta.template;
challenge.time = meta.time;
challenge.helpCategory =
challenge.helpCategory || helpCategoryMap[challenge.block];
challenge.translationPending =
lang !== 'english' && !isAuditedCert(lang, meta.superBlock);
challenge.usesMultifileEditor = !!meta.usesMultifileEditor;
if (challenge.challengeFiles) {
// The client expects the challengeFiles to be an array of polyvinyls
challenge.challengeFiles = challengeFilesToPolys(
challenge.challengeFiles
);
}
if (challenge.solutions?.length) {
// The test runner needs the solutions to be arrays of polyvinyls so it
// can sort them correctly.
challenge.solutions = challenge.solutions.map(challengeFilesToPolys);
}
2020-06-12 12:47:58 +00:00
}
async function createChallenge(filePath, maybeMeta) {
const meta = maybeMeta
? maybeMeta
: require(path.resolve(
META_DIR,
`${getBlockNameFromPath(filePath)}/meta.json`
));
await validate(filePath, meta.superBlock);
const useEnglish =
lang === 'english' ||
!isAuditedCert(lang, meta.superBlock) ||
!fs.existsSync(getFullPath(lang, filePath));
const challenge = await (useEnglish
? parseMD(getFullPath('english', filePath))
: parseTranslation(
getFullPath(lang, filePath),
COMMENT_TRANSLATIONS,
lang
));
addMetaToChallenge(challenge, meta);
return challenge;
}
return createChallenge;
}
function challengeFilesToPolys(files) {
return files.reduce((challengeFiles, challengeFile) => {
return [
...challengeFiles,
{
...createPoly(challengeFile),
seed: challengeFile.contents.slice(0)
}
];
}, []);
}
2020-12-17 14:02:56 +00:00
async function hasEnglishSource(basePath, translationPath) {
const englishRoot = path.resolve(__dirname, basePath, 'english');
2020-12-17 14:02:56 +00:00
return await access(
path.join(englishRoot, translationPath),
fs.constants.F_OK
)
.then(() => true)
.catch(() => false);
}
function getBaseDir(filePath) {
const [baseDir] = filePath.split(path.sep);
return baseDir;
2015-12-07 05:44:34 +00:00
}
function getBlockNameFromPath(filePath) {
2018-10-25 09:54:57 +00:00
const [, block] = filePath.split(path.sep);
return block;
}
2018-11-16 18:22:52 +00:00
2020-12-17 14:02:56 +00:00
exports.hasEnglishSource = hasEnglishSource;
exports.parseTranslation = parseTranslation;
exports.generateChallengeCreator = generateChallengeCreator;