|
| 1 | +const path = require('path'); |
| 2 | +const parseComment = require('comment-parser'); |
| 3 | +const { |
| 4 | + readdirSync, |
| 5 | + readFileSync |
| 6 | +} = require('fs'); |
| 7 | +const { |
| 8 | + isTag, |
| 9 | + getContentFromSource, |
| 10 | + getTitleFromPath, |
| 11 | + getGithubPath, |
| 12 | + isDir |
| 13 | +} = require('./utils'); |
| 14 | + |
| 15 | +const parseSolution = (solutionFile) => { |
| 16 | + const solutionSource = readFileSync(solutionFile, 'utf8'); |
| 17 | + const parsedResult = Object.create(null); |
| 18 | + const parsed = parseComment(solutionSource); |
| 19 | + if (parsed.length <= 0) { |
| 20 | + return null; |
| 21 | + } |
| 22 | + const tags = parsed[0].tags; |
| 23 | + tags.forEach(({tag, source}) => { |
| 24 | + if (isTag(tag)) { |
| 25 | + parsedResult[tag] = getContentFromSource(tag, source); |
| 26 | + } |
| 27 | + }); |
| 28 | + parsedResult.path = getGithubPath(solutionFile); |
| 29 | + return parsedResult; |
| 30 | +}; |
| 31 | + |
| 32 | +const parseCategory = (categoryDir) => { |
| 33 | + const parsedResult = { |
| 34 | + title: getTitleFromPath(categoryDir), |
| 35 | + problems: [], |
| 36 | + }; |
| 37 | + const solutionFiles = readdirSync(categoryDir); |
| 38 | + |
| 39 | + solutionFiles.forEach(solutionFile => { |
| 40 | + const result = parseSolution(path.join(categoryDir, solutionFile)); |
| 41 | + if (result) { |
| 42 | + parsedResult.problems.push(result); |
| 43 | + } |
| 44 | + }); |
| 45 | + return parsedResult; |
| 46 | +}; |
| 47 | + |
| 48 | +const parseSection = (sectionDir) => { |
| 49 | + const parsedResult = { |
| 50 | + title: getTitleFromPath(sectionDir), |
| 51 | + categories: [], |
| 52 | + }; |
| 53 | + const categoryDirs = readdirSync(sectionDir); |
| 54 | + categoryDirs.forEach((categoryDir) => { |
| 55 | + if (isDir(path.join(sectionDir, categoryDir))) { |
| 56 | + const result = parseCategory(path.join(sectionDir, categoryDir)); |
| 57 | + parsedResult.categories.push(result); |
| 58 | + } |
| 59 | + }); |
| 60 | + return parsedResult; |
| 61 | +}; |
| 62 | + |
| 63 | +const parse = (sectionDirs) => { |
| 64 | + const parsedResult = { |
| 65 | + sections: [], |
| 66 | + }; |
| 67 | + sectionDirs.forEach((sectionDir) => { |
| 68 | + if (isDir(sectionDir)) { |
| 69 | + const result = parseSection(path.resolve(sectionDir)); |
| 70 | + parsedResult.sections.push(result); |
| 71 | + } |
| 72 | + }); |
| 73 | + return parsedResult; |
| 74 | +}; |
| 75 | + |
| 76 | +module.exports = parse; |
0 commit comments