getgrit / gritql

GritQL is a query language for searching, linting, and modifying code.
https://docs.grit.io/
MIT License
3.17k stars 82 forks source link

gritql as a formatter/linter for embedded languages #525

Open musjj opened 1 month ago

musjj commented 1 month ago

One of my pet peeves is formatting languages embedded in strings.

For example, with sqlx in rust:

sqlx::query("SELECT * FROM users WHERE email = ?")

Or jq in the shell:

jq '.[0] | {message: .commit.message, name: .commit.committer.name}'

There's currently no generalized tools for formatting this kind of strings, so you usually end up doing it manually.

But I've been thinking that gritql seems like the perfect tool for dealing with this problem. You could write patterns to extract these strings, define an external command to pipe the string to, then use output of the command for your needs.

It could, for example, look like this:

`sqlx::query("$query")` where {
  $formatted = $query |> $(sqlfluff format), // this pipes $query to a shell command
  $query => $formatted
}
morgante commented 1 month ago

I think formatting itself is out of scope for GritQL, but this is a scenario we could likely support in our upcoming workflow engine + SDK. The syntax would look something like this:

grit.rust`sqlx::query("$query")`.each((binding, context) => {
  const query = context.findVar("$query");
  const formatted = $`sqlformat < ${query.text()}`.text();
  query.replace(formatted);
}).run();