From c0b63c53612e9534de16d824bb9da71c623b7795 Mon Sep 17 00:00:00 2001 From: Jon Meow <46229924+jonmeow@users.noreply.github.com> Date: Mon, 22 Jun 2020 11:36:16 -0700 Subject: [PATCH] Help with proper toc labeling (#86) Particularly to fix casing if somebody does "Table of Contents" --- src/scripts/pre-commit-toc.js | 37 +++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) 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);