Syntactically-aware grep for JavaScript and TypeScript

Overview

ESGrep

Syntactically-aware grep for JavaScript and TypeScript

Usage as a CLI

Install it with npm install --global esgrep or the equivalent using pnpm/yarn/etc, then use it as esgrep [OPTION...] PATTERN [FILE...]. If not FILE is precised, reads from stdin. Examples:

// ./example.ts
let x = 10;
const add = () => {
  x++;
};
esgrep 'let x = 10' example.ts
cat example.ts | esgrep 'let x = 10'
esgrep 'let x = 10' example.ts --statement
esgrep --statement -- 'let x = 10' example.ts

The CLI is basically a wrapper around the find lib function and accepts the same options and a few more that handle help print and output format.

Usage as a library

Install it with npm install esgrep or the equivalent using pnpm/yarn/etc, then import it:

import { find, findStrings } from "esgrep";
// or
const { find, findStrings } = require("esgrep");

For now, the lib only targets Node but it's in the roadmap to target Deno and the Web.

Types should be included in the build so refer to them for the exact types of arguments and returned values. This doc focuses on esgrep scenari rather than spec details.

find(pattern, haystack, options?)

pattern and haystack are strings that represent javascript or typescript code which will be matched based on their AST (and not string representation).

options is detailed in options.

find is a Generator that yields estree nodes.

import { find } from "esgrep";

const pattern = "const x = 10";
const haystack = "const x = /* a number */ 10; const y = 20;";
const matches = find(pattern, haystack);
for (const match of matches) {
  console.log(match);
  // {
  //   type: 'VariableDeclaration',
  //   declarations: [ ... ],
  //   kind: 'const',
  //   range: [ 0, 28 ],
  //   loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 28 } }
  // }
}

If you're not comfortable with generators and don't want to use the perf and streaming capabilities they can provide, you can just spread it out into a plain array:

console.log([...matches]);
// [ { type: 'VariableDeclaration', ... }]

findStrings(pattern, haystack, options?)

Basically the same as find but iterates over matched strings rather that matched nodes.

import { findStrings } from "esgrep";

const pattern = "const x = 10";
const haystack = "const x = /* a number */ 10; const y = 20;";
console.log([...findStrings(pattern, haystack)]);
// [ 'const x = /* a number */ 10;' ]

Options

-h, --help (CLI only)

Prints the synopsis and lists CLI options.

esgrep -h

-t, --ts

Include type annotations in the comparison

import { findStrings } from "esgrep";

const withTS = "const x: number = 10";
const withoutTS = "const x = 10";

console.log([...findStrings(withoutTS, withTS)]); // [ 'const x: number = 10' ]
console.log([...findStrings(withoutTS, withTS, { ts: true })]); // []

-s, --statement

If the pattern is an expression statement, lookup the statement itself, and not the expression statement.

import { findStrings } from "esgrep";

const pattern = "10";
const haystack = "const x = 10";
console.log([...findStrings(pattern, haystack)]);
// [ '10' ]
console.log([...findStrings(pattern, haystack, { statement: true })]);
// []

The first search matches the 10 in const x = 10 because it looks up all expressions of 10. In plain English, it looks up all the occurrences of "just" the number 10. That is the most intuitive and default behavior.

The second search does not match the 10 in const x = 10 because it looks up all statements of consisting of only the expression 10. In plain English, statements are anything that makes the exact same sense when adding a ; at the end.

The difference is subtle and it usually takes people not familiar with the concept a few articles to have a good grasp on statements vs expressions. Why not start with this one?

About

Want to report a bug? Don't understant the doc? Suggest an improvement? Open an issue!

Contributions are welcomed, the code is still small, clean, and all in TS, so it should be readable and extendable without additional guidance. For big changes, consider opening an issue before opening a PR.

Coded w/ ♡ by Nino Filiu

You might also like...

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

TypeScript Deep Dive I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack

Jan 4, 2023

This project is a boilerplate for Next and TypeScript projects. This template was built with Vite, TypeScript and Stitches.

This project is a boilerplate for Next and TypeScript projects. This template was built with Vite, TypeScript and Stitches.

Awesome Template Stitches — NextJS, TypeScript, Stitches and Design Tokens Summary About this template Avaliale scripts Other scripts available Main t

Dec 29, 2022

Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's `move-ts`.

Movehat Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's move-ts. Movehat aspires to b

Sep 30, 2022

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Sep 13, 2022

Variant types in Roblox TypeScript - Ported from Vanilla TypeScript

Variant types in Roblox TypeScript - Ported from Vanilla TypeScript

Variant (for Roblox) This is a roblox typescript variant (heh, pun) of Variant. See the Variant documentation on how to use Variant. A variant type is

Jun 3, 2022

A Lua plugin, written in TypeScript, to write TypeScript (Lua optional).

typescript.nvim A minimal typescript-language-server integration plugin to set up the language server via nvim-lspconfig and add commands for convenie

Dec 29, 2022

typescript-to-jsonschema generates JSON Schema files from your Typescript sources.

fast-typescript-to-jsonschema English | 简体中文 a tool generate json schema from typescript. Feature compile Typescript to get all type information conve

Nov 28, 2022

Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript.

Screeps Typescript Starter Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript. It provides everything you need to s

Jan 27, 2022

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Dec 20, 2022
Releases(v1.3.0)
  • v1.3.0(Jun 21, 2022)

    Extracted the CLI logic in order to be testable and easily adapted to non-node runtimes

    Added --format option which defaults to a pretty colorful output that even highlight the code itself

    example

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jun 3, 2022)

    0b384bb feat: ES_NOT d146060 feat: ES_SOME cc36dae feat: ES_EVERY c5092f9 feat: --raw deb844c doc: clearer specs 93eaa9a feat: ES_ANY 2dbeef1 doc: clarify CLI usage

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(May 23, 2022)

  • v1.0.0(May 23, 2022)

    Okay, enough for a v1!

    ESGrep now features a CLI with options and help texts, a typed node library, and a full documentation.

    Hide yo kids, hide yo wife, ESGrep is gonna use abstract syntax trees to find them in your codebase!

    Source code(tar.gz)
    Source code(zip)
  • v0.0.0(May 15, 2022)

    Hello world!

    This is the first release of ESGrep, a syntactically aware grep for JavaScript and TypeScript.

    The goal of the project is to be able to find among many files patterns that are typically very hard to express using regular expressions. For now it only consists of a imperfect lib and a CLI that only find perfect matches, but the base architecture is here and features should be added incrementally in the near future.

    Source code(tar.gz)
    Source code(zip)
Owner
Nino Filiu
Developer & artist | Telecom Paris > Eurecom > TU Berlin > Synomia > 360Learning > Toucan Toco
Nino Filiu
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Apache MXNet (incubating) for Deep Learning Apache MXNet is a deep learning framework designed for both efficiency and flexibility. It allows you to m

The Apache Software Foundation 20.2k Jan 5, 2023
Context-aware smart contracts for blockchain IoT systems

Context-aware smart contracts for blockchain IoT systems It contains 2 directories: contracts: contains the ContextAwareSmartContract.sol contract wit

ibelab 6 Jun 17, 2022
An experimental framework-aware Firebase CLI

Firebase Experimental framework-aware CLI Usage $ npm i -g firebase-frameworks $ cd <MY-APP> $ firebase-frameworks init $ firebase-frameworks build $

null 146 Dec 27, 2022
🔥 Bon5R — Create static, blog-aware websites with pure MDX.

Bon5R Create static, blog-aware websites with pure MDX. Explore the docs » View Demo · Report Bug · Request Feature Table of Contents About The Projec

Manu Anish 3 Jul 5, 2022
Content aware image cropping

smartcrop.js Smartcrop.js implements an algorithm to find good crops for images. It can be used in the browser, in node or via a CLI. Image: https://w

Jonas Wagner 12.5k Jan 4, 2023
Simple time-aware report bot for Telegram.

report bot Built using grammY. Simple time-aware report bot for Telegram. It listens for /report, /admin commands or @admin, @admins mentions in group

Dunkan 11 Oct 2, 2022
A progressively enhanced server-rendered form-aware web component counter using WebC

Eleventy WebC Number Counter Demo A progressively enhanced server-rendered form-aware web component counter using WebC. This enhances from an <input t

Eleventy 6 Nov 11, 2022
Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string

convert-to-dts Converts the source code for any .js or .ts file into the equivalent .d.ts code TypeScript would generate. Usage import { convertToDecl

Lily Scott 11 Mar 3, 2022