question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to programmatically lint code?

See original GitHub issue

I’m currently working on a tool to quickly generate template code based on user preferences (https://github.com/AlCalzone/create-adapter). As part of this, I want to let the user choose his preferred style of quotes. For JS, this is quite easy using the ESLint API:

export function jsFixQuotes(sourceText: string, quotes: "single" | "double"): string {
	const linter = new Linter();
	const result = linter.verifyAndFix(sourceText, {
		// rules here...
	});
	return result.output;
}

I’ve been looking for a way to do that for TypeScript, but I can’t seem to find anything similar in the TSLint docs. Your project seems to support this, but I’m not sure how to use it programmatically.

Can you give me a pointer in the right direction?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
ajafffcommented, Jan 8, 2019

There you have it:

import * as ts from 'typescript';

export enum Quotemark {
    Single = "'",
    Double = '"',
}

export function fixQuotes(source: string, newQuotes: Quotemark) {
    const oldQuotes = newQuotes === Quotemark.Double ? Quotemark.Single : Quotemark.Double;
    // create an AST from the source code, this step is unnecessary if you already have a SourceFile object
    const sourceFile = ts.createSourceFile('quotes.ts', source, ts.ScriptTarget.Latest);
    let resultString = '';
    let lastPos = 0;

    // visit each immediate child node of SourceFile
    ts.forEachChild(sourceFile, function cb(node) {
        if (node.kind === ts.SyntaxKind.StringLiteral && source[node.end - 1] === oldQuotes) {
            // we found a string with the wrong quote style
            const start = node.getStart(sourceFile); // get the position of the opening quotes (this is different from 'node.pos' as it skips all whitespace and comments)
            const rawContent = source.slice(start + 1, node.end - 1); // get the actual contents of the string
            resultString += source.slice(lastPos, start) + newQuotes + escapeQuotes(rawContent, newQuotes, oldQuotes) + newQuotes;
            lastPos = node.end;
        } else {
            // recurse deeper down the AST visiting the immediate children of the current node
            ts.forEachChild(node, cb);
        }

    });
    resultString += source.slice(lastPos);

    return resultString;
}

/** Escape new quotes within the string, unescape the old quotes. */
function escapeQuotes(str: string, newQuotes: Quotemark, oldQuotes: Quotemark) {
    return str.replace(new RegExp(newQuotes, 'g'), `\\${newQuotes}`).replace(new RegExp(`\\\\${oldQuotes}`, 'g'), oldQuotes);
}

Feel free to use it in any way you want. I don’t claim any copyright on this snippet.

If you have any questions, just ask.

1reaction
ajafffcommented, Jan 8, 2019

If you could provide a snippet for that, I would be glad.

@AlCalzone sure thing. I’m trying to get this ready this evening or tomorrow morning.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Invoking Pylint programmatically - python
Take a look at the pylint/epylint.py file which contains two different ways to start Pylint programmatically. You can also simply call
Read more >
What is linting and how can it save you time?
Simply put, a linter is a tool that programmatically scans your code with the goal of finding issues that can lead to bugs...
Read more >
Pylint Static Code Analysis | Executing with Command Line vs ...
First make a python file in your project directory at the same level you ran the above script, I will call it simple.py...
Read more >
Running Pylint — Pylint 2.13.9 documentation
Run() function in the ; pylint.lint module (assuming Pylint options are stored in a list of strings ; pylint_options ) as:.
Read more >
Node.js API - ESLint - Pluggable JavaScript Linter
This class depends on the Node.js fs module and the file system, so you cannot use it in browsers. If you want to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found