All files / builds/1000i100/quiz-maker/src cli.js

0% Statements 0/38
0% Branches 0/1
0% Functions 0/1
0% Lines 0/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                                                                             
#!/usr/bin/env node
const quizMaker = require('./quizMaker.cjs');
const fs = require('fs');
if(process.argv.length < 4) usageError('not enough arguments');
if(process.argv.length > 4) usageError('too many arguments');

let quizSrcFilePath = process.argv[2];
let targetPath = process.argv[3];

if(fs.lstatSync(quizSrcFilePath).isFile()) processOneQuiz(quizSrcFilePath,targetPath);
else if(fs.lstatSync(quizSrcFilePath).isDirectory()){
  const srcPath = trimLastSlash(quizSrcFilePath);

  fs.readdirSync(srcPath).forEach((srcFile)=>processOneQuiz(`${srcPath}/${srcFile}`,targetPath));
} else usageError(`${quizSrcFilePath} is not found as file or directory.`);

function processOneQuiz(src,targetPath){
  targetPath = trimLastSlash(targetPath);
  const quizFileName = src.split('/').pop().split('.').shift();
  const outputFilesStrings = quizMaker(fs.readFileSync(src,"utf8"),quizFileName);
  Object.keys(outputFilesStrings).forEach((fileName)=>{
    const pathParts = [...targetPath.split('/'), ...fileName.split('/')] ;
    pathParts.pop();
    if(pathParts.length>0) fs.mkdirSync(pathParts.join('/'),{recursive: true});
    fs.writeFileSync(`${targetPath}/${fileName}`, outputFilesStrings[fileName])
  });

}
function usageError(customMessage){
  const programName = process.argv[1].split('/').pop();
  if(customMessage) console.error(`\nError : ${customMessage}`);
  console.error(`\nUsage : ${programName} quizSrcFileOrFolder targetFolder`);
  process.exit(1);
}
function trimLastSlash(path){
  if(path[path.length-1] === '/') path = path.substr(0,path.length-1);
  return path;
}