|
| 1 | +import {normalize, join} from 'path'; |
| 2 | +import {readFileSync} from 'fs'; |
| 3 | + |
| 4 | +// TODO: load comments from core-coderoad |
| 5 | + |
| 6 | +const comments = { |
| 7 | + py: '#', |
| 8 | + js: '\/{2,3}', |
| 9 | +}; |
| 10 | + |
| 11 | +function loaderRegex(fileType: string): RegExp { |
| 12 | + let comment = '\/{2,3}'; |
| 13 | + if (comments[fileType]) { |
| 14 | + comment = comments[fileType]; |
| 15 | + } |
| 16 | + return new RegExp(`^${comment} ?load\\(['"](.+)['"](\, ?true)?\\)`, 'm'); |
| 17 | +} |
| 18 | + |
| 19 | +export default function parseLoaders( |
| 20 | + data: string, fileType: string, tutorial: CR.Tutorial, dir: string |
| 21 | +): string { |
| 22 | + |
| 23 | + // loop over lines and add editor files |
| 24 | + let i = -1; |
| 25 | + let lines = data.split('\n'); |
| 26 | + |
| 27 | + let filesLoaded = []; |
| 28 | + let loaderMatch = loaderRegex(fileType); |
| 29 | + |
| 30 | + while (i < lines.length - 1) { |
| 31 | + i += 1; |
| 32 | + let loader: string[] = lines[i].match(loaderMatch); |
| 33 | + |
| 34 | + if (loader) { |
| 35 | + // loader found |
| 36 | + let fileToLoad: string = loader[1]; |
| 37 | + |
| 38 | + if (filesLoaded.indexOf(fileToLoad) > -1) { |
| 39 | + console.log(`"${fileToLoad}" already loaded.`); |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + let pathToFile: string = null; |
| 44 | + if (loader[2]) { |
| 45 | + // path to file from config specified dir |
| 46 | + pathToFile = normalize(join(tutorial.config.dir, fileToLoad)); |
| 47 | + } else { |
| 48 | + // path to file from working directory |
| 49 | + pathToFile = normalize(join(dir, fileToLoad)); |
| 50 | + } |
| 51 | + |
| 52 | + try { |
| 53 | + lines[i] = readFileSync(pathToFile, 'utf8'); |
| 54 | + } catch (e) { |
| 55 | + let message = 'File not found: ' + pathToFile; |
| 56 | + lines[i] = message; |
| 57 | + console.log(message); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return lines.join('\n'); |
| 62 | +} |
0 commit comments