API Reference
CoffeeLint can be used as a library from Node.js or from the browser. Build tools, editor plugins, and test suites use this API to lint source strings and process the results programmatically. This page documents everything exported by the coffeelint package and the helper modules shipped alongside it.
Loading the Library
Node.js
const coffeelint = require('coffeelint');
The package's main entry, lib/coffeelint.js, loads the coffeescript compiler with Node's require.
Browser
lib/coffeelint.js is a Browserify standalone bundle that defines a global coffeelint. It uses window.CoffeeScript, so load the CoffeeScript browser compiler first:
<script src="coffeescript.js"></script>
<script src="coffeelint.js"></script>
If no CoffeeScript compiler is available, loading the library fails.
Quick Example
const fs = require('fs');
const coffeelint = require('coffeelint');
const source = fs.readFileSync('src/cart.coffee', 'utf8');
const config = {
indentation: { level: 'error', value: 2 },
max_line_length: { level: 'warn', value: 100 }
};
const errors = coffeelint.lint(source, config);
for (const e of errors) {
console.log(`${e.lineNumber} [${e.level}] ${e.rule}: ${e.message}`);
}
coffeelint.lint(source, config, literate)
Lints a string of CoffeeScript and returns an array of findings.
| Parameter | Type | Default | Description |
|---|---|---|---|
source |
string |
The CoffeeScript source code. | |
config |
object |
{} |
A configuration object in the same format as coffeelint.json. Unspecified rules use their defaults. |
literate |
boolean |
false |
Treat source as Literate CoffeeScript. |
Returns: an array of lint error objects, sorted by line number. An empty array means the source is clean.
Behavior worth knowing:
lintdoes not discover configuration files. It uses exactly theconfigyou pass. Useconfigfinderto replicate the command line's discovery.- Rules configured with a
modulekey are loaded (and registered) whenlintis called. In the browser, where modules cannot be loaded, this step is skipped silently. transformsand a customcoffeescriptcompiler in thecoffeelintsection are honored. See Transforms and CoffeeScript Flavors.- Inline directives in the source are applied.
- If a cache was set with
setCache, results are read from and written to it.
The Lint Error Object
Each finding is an object built by merging the rule's merged configuration with details about the problem. Common properties:
| Property | Type | Description |
|---|---|---|
rule |
string |
Name of the rule that produced the finding, for example max_line_length. |
name |
string |
Same as rule (copied from the rule configuration). |
level |
string |
error or warn. Findings at level ignore are never returned. |
message |
string |
The rule's message. For coffeescript_error, the compiler's error text. |
lineNumber |
number |
1-based line number. |
lineNumberEnd |
number |
Optional. Last line, for findings that span lines (cyclomatic_complexity). |
context |
string or number |
Optional details, such as Length is 93, max is 80. |
line |
string |
Present for token-based rules: the source line of the finding. |
description |
string |
The rule's documentation (may contain HTML). |
| rule options | various | The rule's options, such as value. |
{
name: 'max_line_length',
value: 80,
level: 'error',
limitComments: true,
message: 'Line exceeds maximum allowed length',
description: '...',
context: 'Length is 93, max is 80',
lineNumber: 12,
rule: 'max_line_length'
}
coffeelint.getErrorReport()
Creates an ErrorReport, which lints several files and summarizes the results. This is what the command line uses internally.
ErrorReport
| Member | Description |
|---|---|
paths |
Object mapping each linted path to its array of error objects. |
lint(filename, source, config = {}, literate = false) |
Lints source with coffeelint.lint and stores the result under filename. |
getErrors(path) |
Returns the findings for path. |
getSummary() |
Returns { errorCount, warningCount, pathCount }. |
hasError() |
true if any path has an error-level finding. |
pathHasError(path) |
true if path has an error-level finding. |
pathHasWarning(path) |
true if path has a warning-level finding. |
getExitCode() |
1 if any path has an error, otherwise 0. |
Example: Lint a List of Files Like the CLI
const fs = require('fs');
const coffeelint = require('coffeelint');
const configfinder = require('coffeelint/lib/configfinder');
const DefaultReporter = require('coffeelint/lib/reporters/default');
const files = ['src/app.coffee', 'src/cart.coffee', 'docs/guide.litcoffee'];
const report = coffeelint.getErrorReport();
for (const file of files) {
const source = fs.readFileSync(file, 'utf8');
const config = configfinder.getConfig(file) || {};
const literate = /\.(litcoffee|coffee\.md)$/.test(file);
report.lint(file, source, config, literate);
}
new DefaultReporter(report, { colorize: process.stdout.isTTY, quiet: false }).publish();
process.exitCode = report.getExitCode();
coffeelint.registerRule(RuleConstructor, ruleName)
Registers a custom rule so that lint runs it. ruleName is optional; when given, it must equal the rule's declared name.
The rule is validated on registration, and an Error beginning with Invalid rule: is thrown if:
- it has no
ruleattribute, or theruleobject lacksname,message, ordescription, ruleNameis given and differs fromrule.name(Mismatched rule name),rule.levelis notignore,warn, orerror,- it implements none of
lintToken,lintLine, orlintAST, - it implements
lintTokenwithout atokensarray.
Registration is global for the loaded library: the rule's defaults are added to coffeelint.RULES, and the rule runs for all later lint calls (according to its configured level). See Writing Custom Rules.
coffeelint.registerRule(require('./rules/no_forbidden_names'));
coffeelint.getRules()
Returns an object with the default configuration of every registered rule (built-in and custom), with keys sorted alphabetically. This is what coffeelint --makeconfig prints (minus each rule's name, message, and description).
coffeelint.RULES
The live object of default rule configurations, keyed by rule name. registerRule adds to it. Treat it as read-only.
coffeelint.trimConfig(userConfig)
Returns the minimal configuration equivalent to userConfig, dropping every setting that matches the defaults. This powers coffeelint --trimconfig.
coffeelint.trimConfig({ indentation: { value: 2 } });
// => {}
coffeelint.trimConfig({ indentation: { value: 4 }, no_tabs: { level: 'error' } });
// => { indentation: { value: 4 } }
Rules set to ignore that are also ignored by default are dropped; rules you set to ignore that are normally active are reduced to { level: 'ignore' }; unknown rule names are dropped.
coffeelint.invertLiterate(source)
Converts Literate CoffeeScript into plain CoffeeScript, where Markdown prose becomes # comments and code blocks are un-indented to their natural position. lint calls this automatically when literate is true; it is exposed for tools that need the same transformation.
coffeelint.setCache(cache)
Enables result caching for subsequent lint calls. The cache object must implement:
| Method | Description |
|---|---|
setConfig(config) |
Called before each lint with the user configuration, so the cache can namespace its entries. |
has(source) |
Whether a result exists for this source. |
get(source) |
Returns the cached array of findings. |
set(source, result) |
Stores the array of findings. |
The file-based implementation used by --cache ships as lib/cache.js:
const path = require('path');
const os = require('os');
const coffeelint = require('coffeelint');
const Cache = require('coffeelint/lib/cache');
coffeelint.setCache(new Cache(path.join(os.tmpdir(), 'coffeelint')));
Its keys combine the CoffeeScript version, the CoffeeLint version, a hash of the configuration, and a hash of the source.
coffeelint.VERSION
The version string of the library, for example '2.1.0'.
Helper Modules
The npm package also ships the compiled modules the command line uses. They are not part of the main export but can be required directly.
configfinder
const configfinder = require('coffeelint/lib/configfinder');
const config = configfinder.getConfig('src/app.coffee');
getConfig(filename) runs the same discovery as the command line (environment variable, package.json, coffeelint.json, home directory) starting from the file's directory, applies extends, and resolves module paths. Without a filename it starts from the current directory. It returns undefined or null when nothing is found. See Configuration.
ruleLoader
const ruleLoader = require('coffeelint/lib/ruleLoader');
ruleLoader.loadRule(coffeelint, 'coffeelint-my-rule');
| Method | Description |
|---|---|
require(moduleName) |
Resolves a module from the current directory, then globally, then as a path relative to the current directory. |
loadRule(coffeelint, moduleName, ruleName) |
Loads a module exporting one rule class (or an array of them) and registers it. Logs Error loading <module> and rethrows on failure. |
loadFromConfig(coffeelint, config) |
Loads every rule in config that has a module key. |
Reporters
The built-in reporters live in lib/reporters/ (default, csv, jslint, checkstyle, raw). Each is a class constructed with (errorReport, { colorize, quiet }) that prints its output from publish(). See Reporters.