Using ripgrep and .rgignore to efficiently search for code

This is partly to document it for myself :slight_smile:

We all know grep and perhaps ack but I’m using ripgrep. Benefits include that by default it reads .gitignore so you’re not searching in generated files. Often I want to find some string in the code and ripgrep is very fast. An example:

$ time rg 'not recognized'
lib/tasks/model.rake
80:  puts "Models that were not recognized and converted: " + (Model.all - mapped).map(&:name).to_sentence

app/models/smart_proxy.rb
110:          errors.add :base, _('Features "%s" in this proxy are not recognized by Foreman. '\

test/controllers/operatingsystems_controller_test.rb
110:      assert_match /not recognized for searching/, flash[:error]

test/controllers/compute_resources_controller_test.rb
173:      assert_match /not recognized for searching/, flash[:error]

test/models/smart_proxy_test.rb
81:    error_message = 'Features "feature" in this proxy are not recognized by Foreman. '\

real	0m0,043s
user	0m0,048s
sys	0m0,042s

Within a second I know that the code I’m looking for is in app/models/smart_proxy.rb. For comparison, grep:

time grep 'not recognized' -R .
[...]

real	0m8,906s
user	0m0,865s
sys	0m1,884s

I’ve trimmed the grep output because it searches in node_modules and a lot more so it’s rather useless.

To get that very useful ripgrep output I had to ignore the locales. Especially the javascript locales really break your output because it’s one huge line. Luckily you can ignore things. On the command line you can pass --glob '!app/assets/javascripts/locale' but that gets tiring. You can also create a .rgignore file containing the paths (.gitignore style).

2 Likes

git grep is also useful, although probably not quite as flexible as ripgrep

$ time git grep 'not recognized' './*' ':!app/assets/javascripts/locale' ':!locale'
app/models/smart_proxy.rb:          errors.add :base, _('Features "%s" in this proxy are not recognized by Foreman. '\
lib/tasks/model.rake:  puts "Models that were not recognized and converted: " + (Model.all - mapped).map(&:name).to_sentence
test/controllers/compute_resources_controller_test.rb:      assert_match /not recognized for searching/, flash[:error]
test/controllers/operatingsystems_controller_test.rb:      assert_match /not recognized for searching/, flash[:error]
test/models/smart_proxy_test.rb:    error_message = 'Features "feature" in this proxy are not recognized by Foreman. '\

real	0m0.027s
user	0m0.025s
sys	0m0.059s