diff --git a/src/scripts/pre-commit-toc.js b/src/scripts/pre-commit-toc.js index 4a95b2793a6e..23a4f310aa67 100755 --- a/src/scripts/pre-commit-toc.js +++ b/src/scripts/pre-commit-toc.js @@ -17,12 +17,41 @@ from https://github.com/jonschlinkert/markdown-toc. const mdtoc = require('markdown-toc'); const fs = require('fs'); +var error = 0; const files = process.argv.slice(2); for (var i = 0; i < files.length; ++i) { - const oldContent = fs.readFileSync(files[i]).toString(); - const newContent = mdtoc.insert(oldContent, { bullets: '-' }); + const file = files[i]; + const oldContent = fs.readFileSync(file).toString(); + var newContent = oldContent; + + // Only process files with the toc indicator. + if (!oldContent.match(//m)) continue; + + // If there's a case-incorrect toc section, fix casing. + newContent = newContent.replace( + /\n## Table of contents\n\n\n/im, + '\n## Table of contents\n\n\n' + ); if (oldContent != newContent) { - console.log(`Updating ${files[i]}`); - fs.writeFileSync(files[i], newContent); + console.log(`Fixed "Table of contents" header in ${file}`); + } + + // Ensure the file properly labels the toc. + if (!newContent.match(/\n## Table of contents\n\n\n/m)) { + error = 1; + console.log( + `${file} has a toc without a "Table of contents" header. Use:\n` + + ' ## Table of contents\n\n \n' + ); + continue; + } + + // Do the toc substitution. + newContent = mdtoc.insert(newContent, { bullets: '-' }); + + if (oldContent != newContent) { + console.log(`Updating ${file}`); + fs.writeFileSync(file, newContent); } } +process.exit(error);