New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

leasot

Package Overview
Dependencies
Maintainers
1
Versions
124
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

leasot

Parse and output TODOs and FIXMEs from comments in your files

  • 6.2.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

leasot

Parse and output TODOs and FIXMEs from comments in your files

NPM Version NPM Downloads Build Status code style: prettier

Easily extract, collect and report TODOs and FIXMEs in your code. This project uses regex in order to extract your todos from comments.

Basic output example of leasot

Comment format

TODO: add some info

  • Spaces are optional.
  • Colon is optional.
  • Must be in a comment (line or block) in its' own line (some code(); //TODO: do something is not supported).
  • Can be prefixed with a @ (i.e @TODO).
  • Spaces are trimmed around comment text.
  • Supported default types are TODO and FIXME - case insensitive.
  • Additional types can be added (using tags in cli and customTags in leasot.parse)
  • New extensions can be associated with bundled parsers as many languages have overlapping syntax
  • Supports both leading and trailing references. E.g. // TODO(tregusti): Make this better or // TODO: Text /tregusti

Supported languages:

FiletypeExtensionNotesParser Name
C#.csSupports // and /* */ comments.defaultParser
C++/C.cpp .c .hSupports // and /* */ comments.defaultParser
Coffee-React.cjsxSupports # comments.coffeeParser
Coffeescript.coffeeSupports # comments.coffeeParser
Crystal.crSupports # comments.coffeeParser
CSon.csonSupports # comments.coffeeParser
CSS.cssSupports /* */ comments.defaultParser
EJS.ejsSupports <!-- --> and <%# %>ejsParser
Erb.erbSupports <!-- --> and <%# %>ejsParser
Erlang.erl .hrlSupports % comments.erlangParser
Go.goSupports // and /* */ comments.defaultParser
Haml.hamlSupports / -# <!-- --> and <%# %>twigParser
Handlebars.hbs .handlebarsSupports {{! }} and {{!-- --}}hbsParser
Haskell.hsSupports --haskellParser
Hogan.hgn .hoganSupports {{! }} and {{!-- --}}hbsParser
HTML.html .htmSupports <!-- -->twigParser
Jade.jade .pugSupports // and //- comments.jadeParser
Java.javaSupports // and /* */ commentsdefaultParser
Javascript.js .es .es6Supports // and /* */ commentsdefaultParser
Jsx.jsxSupports // and /* */ comments.defaultParser
Kotlin.ktSupports // and /* */ comments.defaultParser
Less.lessSupports // and /* */ comments.defaultParser
Mustache.mustacheSupports {{! }} and {{!-- --}}hbsParser
Nunjucks.njkSupports {# #} and <!-- -->twigParser
Objective-C.mSupports // and /* */ commentsdefaultParser
Objective-C++.mmSupports // and /* */ commentsdefaultParser
Pascal.pasSupports // and { } comments.pascalParser
Perl.pl, .pmSupports # comments.coffeeParser
PHP.phpSupports // and /* */ comments.defaultParser
Python.pySupports """ and # comments.pythonParser
Ruby.rbSupports # comments.coffeeParser
Sass.sass .scssSupports // and /* */ comments.defaultParser
Scala.scalaSupports // and /* */ comments.defaultParser
Shell.sh .zsh .bashSupports # comments.coffeeParser
SilverStripe.ssSupports <%-- --%> comments.ssParser
SQL.sqlSupports -- and /* */ commentsdefaultParser & haskellParser
Stylus.stylSupports // and /* */ comments.defaultParser
Swift.swiftSupports // and /* */ comments.defaultParser
Twig.twigSupports {# #} and <!-- -->twigParser
Typescript.ts, .tsxSupports // and /* */ comments.defaultParser
Vue.vueSupports // /* */ <!-- --> comments.twigParser
Yaml.yaml .ymlSupports # comments.coffeeParser

Javascript is the default parser.

PRs for additional filetypes is most welcomed!!

Usage

Command Line

Installation
$ npm install --global leasot
Examples
$ leasot --help

  Usage: leasot [options] <file ...>

  Parse and output TODOs and FIXMEs from comments in your files

  Options:

    -h, --help                           output usage information
    -V, --version                        output the version number
    -A, --associate-parser [ext,parser]  associate unknown extensions with bundled parsers (parser optional / default: defaultParser)
    -i, --ignore <patterns>              add ignore patterns
    -I, --inline-files                   parse possible inline files
    -r, --reporter [reporter]            use reporter (table|json|xml|markdown|vscode|raw) (default: table)
    -S, --skip-unsupported               skip unsupported filetypes
    -t, --filetype [filetype]            force the filetype to parse. Useful for streams (default: .js)
    -T, --tags <tags>                    add additional comment types to find (alongside todo & fixme)
    -x, --exit-nicely                    exit with exit code 0 even if todos/fixmes are found

  Examples:

    # Check a specific file
    $ leasot index.js

    # Check php files with glob
    $ leasot **/*.php

    # Check multiple different filetypes
    $ leasot app/**/*.js test.rb

    # Use the json reporter
    $ leasot --reporter json index.js

    # Search for REVIEW comments as well
    $ leasot --tags review index.js

    # Add ignore pattern to filter matches
    $ leasot app/**/*.js --ignore "**/custom.js"

    # Search for REVIEW comments as well
    $ leasot --tags review index.js

    # Check a stream specifying the filetype as coffee
    $ cat index.coffee | leasot --filetype .coffee

    # Report from leasot parsing and filter todos using `jq`
    $ leasot tests/**/*.styl --reporter json | jq 'map(select(.kind == "TODO"))' | leasot-reporter
Using in NPM

This package.json snippet shows how to include leasot in your project development environment and set up as a task (todo). The todo_suppress_error task stops leasot causing npm to error, so it can be used in a build process without halting it.

{
    "scripts": {
        "todo": "leasot src/**/*.js",
        "todo_suppress_error": "leasot src/**/*.js || true"
    },
    "devDependencies": {
        "leasot": "*"
    }
}

Programmatic

Installation
$ npm install --save-dev leasot
Examples
const fs = require('fs');
const leasot = require('leasot');

const contents = fs.readFileSync('./contents.js', 'utf8');
// get the filetype of the file, or force a special parser
const filetype = path.extname('./contents.js');
// add file for better reporting
const file = 'contents.js';
const todos = leasot.parse({ ext: filetype, content: contents, fileName: file });

// -> todos now contains the array of todos/fixme parsed

const output = leasot.reporter(todos, {
    reporter: 'json',
    spacing: 2
});

console.log(output);
// -> json output of the todos

Build Time

API

const leasot = require('leasot');

leasot exposes the following API:

.associateExtWithParser(parsers)

Associates a parser with a new extension.

The parsers parameter must be completed in the following format:

{
    '.cls': {
        parserName: 'defaultParser'
    }
}

The parserName property can also be an array of parser names.

{
    '.sql': {
        parserName: ['defaultParser', 'haskellParser']
    }
}

.isExtSupported(extension)

Check whether extension is supported by a built-in parser.

Specify an extension including the prefixing dot, for example:

leasot.isExtSupported('.js'); //-> true

Returns: Boolean

.parse(options)

NameTypeRequiredDefaultDescription
extstringYesThe extension the parse as including a prefixing dot.
contentstringYesContent to parse
associateParserobjectNoSee .associateExtWithParser for syntax
customParsersobjectNoSee Custom Parsers for syntax
customTagsarrayNo[]Additional tags (comment types) to search for (alongside todo & fixme)
fileNamestringNofileName to attach to todos output
withIncludedFilesbooleanNofalseParse also possible included file types (for example: css inside a php file

Returns: array of comments.

[{
    file: 'parsedFile.js',
    text: 'comment text',
    kind: 'TODO',
    line: 8,
    ref: 'reference'
}]

Note that tags are case-insensitive and are strict matching, i.e PROD tag will match PROD but not PRODUCTS

Custom Parsers

Custom parsers can be supplied via the customParsers option to the parse programmatic api. These are in the format:

{
    '<parserName>': () => parserFactory
}

Example:

const leasot = require('leasot');

const todos = leasot.parse({
        ext: filetype,
        content: contents,
        fileName: file,
        associateParser: {
            '.myExt1': { parserName: 'myCustomParser1' },
            '.myExt2': { parserName: 'myCustomParser2' },
        },
        customParsers: {
            myCustomParser1: function (parseOptions) {
                return function parse(contents, file) {
                    const comments = [];
                     comments.push({
                        file: '',   // The file path, eg |file || 'unknown file'""
                        kind: '',   // One of the keywords such as `TODO` and `FIXME`.
                        line: 0,    // The line number
                        text: '',   // The comment text
                        ref: ''     // The optional (eg. leading and trailing) references in the comment
                    });
                    return comments;
                }
            },
            myCustomParser2: function (parseOptions) {
                // etc
            },
        }
    });

Note as above you will need to associate any new extensions using associateExtWithParser. You can overwrite the built in parsers by naming them the same, eg, overwrite the default parser:

 customParsers: {
        defaultParser: function (parseOptions) {
            // etc
        }
    }

See the built-in parsers for examples

Utils

There are some built in utils for todo parsing that may be useful for custom parsers:

const leasot = require('leasot');
const prepareComment = require('leasot/lib/utils/comments').prepareComment;

const todos = leasot.parse({
        ext: '.myExt',
        content: contents,
        fileName: file,
        associateParser: {
            '.myExt': { parserName: 'myCustomParser' },
        },
        customParsers: {
            myCustomParser: function (parseOptions) {
                return function parse(contents, file) {
                    const comment = prepareComment(match, index + 1, file);
                    comments.push(comment);
                    return comments;
                }
            }
        }
    });

.reporter(comments, config)

Use the specified reporter to report the comments.

comments is the array of comments received from leasot.parse().

config is an object that will also be passed to the reporter itself (allowing custom options for each reporter).

It may also contain the specified reporter:

config.reporter

Can be a string indicating the built-in reporter to use, or an external library used as a reporter.

Could also be a custom function (comments, config)

Type: String|Function

Required: false

Default: raw

Built-in Reporters

  • json
  • xml
  • raw
  • table
  • markdown
  • vscode

Each reporter might contain config params that are useful only for that reporter:

Markdown

Returns a markdown version of the todos.

Options

newLine

How to separate lines in the output file. Defaults to your OS's default line separator.

Type: String

Default: Your system default line feed

padding

How many newLines should separate between comment type blocks.

Type: Number

Default: 2

Minimum: 0

transformHeader(kind)

Control the output of a header for each comment kind (i.e todo, fixme).

Type: Function

Default:

transformHeader: function (kind) {
    return ['### ' + kind + 's',
        '| Filename | line # | ' + kind,
        '|:------|:------:|:------'
    ];
}

kind: will be be passed as the comment kind (todo/fixme).

Returns: String[]|String

You are expected to return either an Array of strings or just a string. If you return an array - each item will be separated by a newline in the output.

transformComment(file, line, text, kind, ref)

Control the output for each comment.

Type: Function

Default:

transformComment: function (file, line, text, kind, ref) {
    return ['| ' + file + ' | ' + line + ' | ' + text];
}

file: filename the comment was in.

line: line of comment.

text: comment text. Default ''.

kind: will be be passed as the comment kind (todo/fixme).

ref: a reference. Default ''.

Returns: String[]|String

You are expected to return either an Array of strings or just a string. If you return an array - each item will be separated by a newline in the output.

VSCode

Returns a markdown version of the todos customized for Visual Studio Code. The file names are transformed as URLs and the line numbers as anchors which makes them clickable when the markdown content produced with this reporter is opened on Visual Studio Code.

Table

Returns a pretty formatted table of the todos.

Raw

Just returns the raw javascript todos

JSON

Return a JSON valid representation of the todos.

Options
spacing

Type: Number

Default: 2

XML

Return an unformatted XML valid representation of the todos.

Parsed using json2xml

Options
header

Whether to include xml header

Type: Boolean

Default: true

attributes_key

See https://github.com/estheban/node-json2xml#options--behaviour

Type: Boolean

Default: undefined

License

MIT ©Gilad Peleg

Keywords

FAQs

Package last updated on 21 Apr 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc