Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: thlorenz/doctoc
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v1.4.0
Choose a base ref
...
head repository: thlorenz/doctoc
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v2.0.0
Choose a head ref
  • 18 commits
  • 9 files changed
  • 10 contributors

Commits on Mar 1, 2019

  1. expose API in top level (#160)

    * expose API in top level
    
    * updated API
    alexandru-constantin authored and AndrewSouthpaw committed Mar 1, 2019
    Copy the full SHA
    e4c74ae View commit details

Commits on Jul 26, 2019

  1. Create FUNDING.yml

    thlorenz committed Jul 26, 2019
    Copy the full SHA
    427b21a View commit details

Commits on Aug 11, 2020

  1. add --entire flag

    sarisia committed Aug 11, 2020
    Copy the full SHA
    405b035 View commit details

Commits on Oct 12, 2020

  1. Make commands explicit and update npm versions (#180)

    José Eduardo Montenegro Cavalcanti de Oliveira authored Oct 12, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    de06803 View commit details

Commits on Oct 13, 2020

  1. change --entire to --all

    sarisia committed Oct 13, 2020
    Copy the full SHA
    41bd8ff View commit details
  2. 7
    Copy the full SHA
    751f031 View commit details
  3. add --all flag (#186)

    Supersedes #183
    AndrewSouthpaw authored Oct 13, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f146558 View commit details

Commits on Oct 14, 2020

  1. feat: flag to keep file without toc untouched

    add cli flag to prevent doctoc from adding toc to a file without toc.
    this is good for CI or a combination with lint-staged.
    with -p, doctoc will update toc if md has toc sectioon, otherwise doctoc keep it unmodified.
    uetchy committed Oct 14, 2020
    Copy the full SHA
    617c7c5 View commit details
  2. Copy the full SHA
    2be533d View commit details
  3. Copy the full SHA
    04ffd96 View commit details
  4. Copy the full SHA
    88e4c56 View commit details

Commits on Oct 15, 2020

  1. fix: update notice text

    uetchy authored Oct 15, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f07f3aa View commit details

Commits on Oct 22, 2020

  1. Merge pull request #181 from uetchy/preserve

    add cli flag to prevent doctoc from adding toc to a file without toc.
    this is good for CI or the combination with [`lint-staged`](https://github.com/okonet/lint-staged).
    with -p, doctoc will update toc if md has toc sectioon, otherwise doctoc keep it unmodified.
    
    I'm not sure `preserve` is the right name for it. so please change it if you have a better one.
    AndrewSouthpaw authored Oct 22, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    88ec7cd View commit details
  2. collapse consecutive blank lines if there's no title (closes #101) (#145

    )
    
    Closes #101
    
    ## before
    
        # example
    
        <!-- START doctoc generated TOC please keep comment here to allow auto update -->
        <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
    
    
        - [NAME](#name)
        - [SYNOPSIS](#synopsis)
        - [DESCRIPTION](#description)
        - [EXPORTS](#exports)
          - [foo](#foo)
          - [bar](#bar)
          - [baz](#baz)
        - [SEE ALSO](#see-also)
        - [AUTHOR](#author)
        - [COPYRIGHT AND LICENSE](#copyright-and-license)
    
        <!-- END doctoc generated TOC please keep comment here to allow auto update -->
    
    ## after
    
        # example
    
        <!-- START doctoc generated TOC please keep comment here to allow auto update -->
        <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
    
        - [NAME](#name)
        - [SYNOPSIS](#synopsis)
        - [DESCRIPTION](#description)
        - [EXPORTS](#exports)
          - [foo](#foo)
          - [bar](#bar)
          - [baz](#baz)
        - [SEE ALSO](#see-also)
        - [AUTHOR](#author)
        - [COPYRIGHT AND LICENSE](#copyright-and-license)
    
        <!-- END doctoc generated TOC please keep comment here to allow auto update -->
    chocolateboy authored Oct 22, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    bf7896b View commit details
  3. pre-commit docs: update sha -> rev (#178)

    Since pre-commit [v1.7.0](https://github.com/pre-commit/pre-commit/blob/master/CHANGELOG.md#170---2018-03-03), `rev` is the preferred spelling for that field
    asottile authored Oct 22, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    d38d04b View commit details
  4. Update dependencies to fix deprecation warnings (#179)

    * Update dependencies to fix deprecation warnings
    
    Fixes the following deprecations:
    
        npm WARN deprecated request@2.79.0: request has been deprecated, see request/request#3142
        npm WARN deprecated hawk@3.1.3: This module moved to @hapi/hawk. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues.
        npm WARN deprecated cryptiles@2.0.5: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
        npm WARN deprecated hoek@2.16.3: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
        npm WARN deprecated boom@2.10.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
        npm WARN deprecated sntp@1.0.9: This module moved to @hapi/sntp. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues.
        npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
    
    And some vulnerabilities:
    
        found 58 vulnerabilities (26 low, 7 moderate, 24 high, 1 critical)
          run `npm audit fix` to fix them, or `npm audit` for details
    
    * Switch to tilde ranges for dependencies
    
    Co-authored-by: Andrew Smith <andrewsmith@alumni.stanford.edu>
    lydell and AndrewSouthpaw authored Oct 22, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    9bc2c83 View commit details

Commits on Nov 10, 2020

  1. Bump lodash from 4.17.15 to 4.17.20 (#187)

    Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.20.
    - [Release notes](https://github.com/lodash/lodash/releases)
    - [Commits](lodash/lodash@4.17.15...4.17.20)
    
    Signed-off-by: dependabot[bot] <support@github.com>
    
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
    dependabot[bot] authored Nov 10, 2020

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    68af396 View commit details

Commits on Dec 4, 2020

  1. 2.0.0

    thlorenz committed Dec 4, 2020
    1
    Copy the full SHA
    2faf563 View commit details
Showing with 3,810 additions and 32 deletions.
  1. +3 −0 .github/FUNDING.yml
  2. +14 −6 .travis.yml
  3. +6 −2 README.md
  4. +17 −5 doctoc.js
  5. +11 −5 lib/transform.js
  6. +3,677 −0 package-lock.json
  7. +11 −11 package.json
  8. +0 −1 test/transform-title.js
  9. +71 −2 test/transform.js
3 changes: 3 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
github: thlorenz
patreon: thlorenz
custom: ['paypal.me/thlorenz']
20 changes: 14 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
language: node_js

os: linux

dist: bionic

node_js:
- 0.10
- 0.12
- 4
- 6
- 8
- 9
- 10 # Previous LST
- 12.18.1 # Actual LTS
- 14.4.0 # Latest version

install: npm install

script: npm test

cache: npm
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -123,7 +123,7 @@ Running doctoc will insert the toc at that location.

Use the `--title` option to specify a (Markdown-formatted) custom TOC title; e.g., `doctoc --title '**Contents**' .` From then on, you can simply run `doctoc <file>` and doctoc will will keep the title you specified.

Alternatively, to blank out the title with a newline, use the `--notitle` option. This will simply remove the title from the TOC.
Alternatively, to blank out the title, use the `--notitle` option. This will simply remove the title from the TOC.

### Specifying a maximum heading level for TOC entries

@@ -140,6 +140,10 @@ You can print to stdout by using the `-s` or `--stdout` option.

[ack]: http://beyondgrep.com/

### Only update existing ToC

Use `--update-only` or `-u` to only update the existing ToC. That is, the Markdown files without ToC will be left untouched. It is good if you want to use `doctoc` with `lint-staged`.

### Usage as a `git` hook

doctoc can be used as a [pre-commit](http://pre-commit.com) hook by using the
@@ -148,7 +152,7 @@ following configuration:
```yaml
repos:
- repo: https://github.com/thlorenz/doctoc
sha: ... # substitute a tagged version
rev: ... # substitute a tagged version
hooks:
- id: doctoc
```
22 changes: 17 additions & 5 deletions doctoc.js
Original file line number Diff line number Diff line change
@@ -16,13 +16,21 @@ function cleanPath(path) {
return homeExpanded.replace(/\s/g, '\\ ');
}

function transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPrefix, stdOut) {
function transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, stdOut, updateOnly) {
if (processAll) {
console.log('--all flag is enabled. Including headers before the TOC location.')
}

if (updateOnly) {
console.log('--update-only flag is enabled. Only updating files that already have a TOC.')
}

console.log('\n==================\n');

var transformed = files
.map(function (x) {
var content = fs.readFileSync(x.path, 'utf8')
, result = transform(content, mode, maxHeaderLevel, title, notitle, entryPrefix);
, result = transform(content, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, updateOnly);
result.path = x.path;
return result;
});
@@ -54,7 +62,7 @@ function printUsageAndExit(isErr) {

var outputFunc = isErr ? console.error : console.info;

outputFunc('Usage: doctoc [mode] [--entryprefix prefix] [--notitle | --title title] [--maxlevel level] <path> (where path is some path to a directory (e.g., .) or a file (e.g., README.md))');
outputFunc('Usage: doctoc [mode] [--entryprefix prefix] [--notitle | --title title] [--maxlevel level] [--all] [--update-only] <path> (where path is some path to a directory (e.g., .) or a file (e.g., README.md))');
outputFunc('\nAvailable modes are:');
for (var key in modes) {
outputFunc(' --%s\t%s', key, modes[key]);
@@ -75,7 +83,7 @@ var modes = {
var mode = modes['github'];

var argv = minimist(process.argv.slice(2)
, { boolean: [ 'h', 'help', 'T', 'notitle', 's', 'stdout'].concat(Object.keys(modes))
, { boolean: [ 'h', 'help', 'T', 'notitle', 's', 'stdout', 'all' , 'u', 'update-only'].concat(Object.keys(modes))
, string: [ 'title', 't', 'maxlevel', 'm', 'entryprefix' ]
, unknown: function(a) { return (a[0] == '-' ? (console.error('Unknown option(s): ' + a), printUsageAndExit(true)) : true); }
});
@@ -93,7 +101,9 @@ for (var key in modes) {
var title = argv.t || argv.title;
var notitle = argv.T || argv.notitle;
var entryPrefix = argv.entryprefix || '-';
var processAll = argv.all;
var stdOut = argv.s || argv.stdout
var updateOnly = argv.u || argv['update-only']

var maxHeaderLevel = argv.m || argv.maxlevel;
if (maxHeaderLevel && isNaN(maxHeaderLevel) || maxHeaderLevel < 0) { console.error('Max. heading level specified is not a positive number: ' + maxHeaderLevel), printUsageAndExit(true); }
@@ -110,7 +120,9 @@ for (var i = 0; i < argv._.length; i++) {
files = [{ path: target }];
}

transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPrefix, stdOut);
transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, stdOut, updateOnly);

console.log('\nEverything is OK.');
}

module.exports.transform = transform;
16 changes: 11 additions & 5 deletions lib/transform.js
Original file line number Diff line number Diff line change
@@ -85,8 +85,8 @@ function countHeaders (headers) {
return headers;
}

function getLinesToToc (lines, currentToc, info) {
if (!currentToc) return lines;
function getLinesToToc (lines, currentToc, info, processAll) {
if (processAll || !currentToc) return lines;

var tocableStart = 0;

@@ -106,7 +106,7 @@ function determineTitle(title, notitle, lines, info) {
return info.hasStart ? lines[info.startIdx + 2] : defaultTitle;
}

exports = module.exports = function transform(content, mode, maxHeaderLevel, title, notitle, entryPrefix) {
exports = module.exports = function transform(content, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, updateOnly) {
mode = mode || 'github.com';
entryPrefix = entryPrefix || '-';

@@ -116,10 +116,16 @@ exports = module.exports = function transform(content, mode, maxHeaderLevel, tit
var lines = content.split('\n')
, info = updateSection.parse(lines, matchesStart, matchesEnd)

if (!info.hasStart && updateOnly) {
return { transformed: false };
}

var inferredTitle = determineTitle(title, notitle, lines, info);

var titleSeparator = inferredTitle ? '\n\n' : '\n';

var currentToc = info.hasStart && lines.slice(info.startIdx, info.endIdx + 1).join('\n')
, linesToToc = getLinesToToc(lines, currentToc, info);
, linesToToc = getLinesToToc(lines, currentToc, info, processAll);

var headers = getMarkdownHeaders(linesToToc, maxHeaderLevel)
.concat(getHtmlHeaders(linesToToc, maxHeaderLevelHtml))
@@ -139,7 +145,7 @@ exports = module.exports = function transform(content, mode, maxHeaderLevel, tit

var toc =
inferredTitle
+ '\n\n'
+ titleSeparator
+ linkedHeaders
.map(function (x) {
var indent = _(_.range(x.rank - lowestRank))
3,677 changes: 3,677 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -2,29 +2,29 @@
"author": "Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)",
"name": "doctoc",
"description": "Generates TOC for markdown files of local git repo.",
"version": "1.4.0",
"version": "2.0.0",
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/doctoc.git"
},
"scripts": {
"test": "set -e; for t in test/*.js; do node $t; done"
},
"files": [
"lib"
],
"main": "doctoc.js",
"bin": "doctoc.js",
"engines": {
"node": ">=0.4"
},
"dependencies": {
"@textlint/markdown-to-ast": "~6.0.9",
"anchor-markdown-header": "^0.5.5",
"htmlparser2": "~3.9.2",
"minimist": "~1.2.0",
"underscore": "~1.8.3",
"update-section": "^0.3.0"
"@textlint/markdown-to-ast": "~6.1.7",
"anchor-markdown-header": "~0.5.7",
"htmlparser2": "~4.1.0",
"minimist": "~1.2.5",
"underscore": "~1.10.2",
"update-section": "~0.3.3"
},
"devDependencies": {
"tap": "~10.2.1"
"tap": "^14.10.7"
},
"license": "MIT",
"keywords": [
1 change: 0 additions & 1 deletion test/transform-title.js
Original file line number Diff line number Diff line change
@@ -45,7 +45,6 @@ test('\nclobber existing title', function (t) {
t.deepEqual(
headers.toc.split('\n')
, [ '',
'',
'- [Installation](#installation)',
'- [API](#api)',
'- [License](#license)',
73 changes: 71 additions & 2 deletions test/transform.js
Original file line number Diff line number Diff line change
@@ -8,9 +8,9 @@ function inspect(obj, depth) {
console.log(require('util').inspect(obj, false, depth || 5, true));
}

function check(md, anchors, mode, maxHeaderLevel, title, notitle, entryPrefix) {
function check(md, anchors, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll) {
test('transforming', function (t) {
var res = transform(md, mode, maxHeaderLevel, title, notitle, entryPrefix)
var res = transform(md, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll)

// remove wrapper
var data = res.data.split('\n');
@@ -284,6 +284,75 @@ test('transforming when old toc exists', function (t) {
t.end()
})

test('transforming when old toc exists and --all flag is set', function (t) {
var md = [
'# Header above'
, ''
, 'The above header should be ignored since it is above the existing toc'
, ''
, '<!-- START doctoc generated TOC please keep comment here to allow auto update -->'
, '<!-- DON\'T EDIT THIS SECTION INSTEAD RE-RUN doctoc TO UPDATE -->'
, '**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*'
, ''
, '- [OldHeader](#oldheader)'
, ''
, '<!-- END doctoc generated TOC please keep comment here to allow auto update -->'
, '## Header'
, 'some content'
, ''
].join('\n')

var res = transform(md, undefined, undefined, undefined, undefined, undefined, true)

t.ok(res.transformed, 'transforms it')

t.deepEqual(
res.toc.split('\n')
, [ '**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*',
'',
'- [Header above](#header-above)',
' - [Header](#header)',
'' ]
, 'replaces old toc'
)

t.deepEqual(
res.wrappedToc.split('\n')
, [ '<!-- START doctoc generated TOC please keep comment here to allow auto update -->',
'<!-- DON\'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->',
'**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*',
'',
'- [Header above](#header-above)',
' - [Header](#header)',
'',
'<!-- END doctoc generated TOC please keep comment here to allow auto update -->'
]
, 'wraps old toc'
)

t.deepEqual(
res.data.split('\n')
, [ '# Header above',
'',
'The above header should be ignored since it is above the existing toc',
'',
'<!-- START doctoc generated TOC please keep comment here to allow auto update -->',
'<!-- DON\'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->',
'**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*',
'',
'- [Header above](#header-above)',
' - [Header](#header)',
'',
'<!-- END doctoc generated TOC please keep comment here to allow auto update -->',
'## Header',
'some content',
'' ]
, 'updates the content with the new toc and ignores header before existing toc'
)
t.end()
})


// bigbucket.org
check(
[ '# My Module'