Mercurial “git grep” equivalent extension

As we are used to git when working on mercurial we miss a lot the “git grep” command as “hg grep” doesn’t really do the same thing. So we managed to quickly create a mercurial extension to add the hgrep command to hg which behaves a bit like git grep.

import itertools, os, os.path
 
def hgrep(ui, repo, what, **opts):
    files = []
    status = repo.status(clean=True)
 
    for f in itertools.chain(status[0], status[1], status[4], status[6]):
        files.append(os.path.join(repo.root, f))
 
    os.system("grep %s %s" % (what, ' '.join(files)))
 
cmdtable = {"hgrep": (hgrep, [], "[what]")}

To have the “hg hgrep” command and make it work just save it as hgrep.py in your python modules path and add it to ~/.hgrc inside the extensions section like:

[extensions]
hgrep =

Then you will be able to run “hg grep what” inside a mercurial repository and it will find each file at its current state that contains what you were looking for giving you the complete absolute path to the file.

2 thoughts on “Mercurial “git grep” equivalent extension

  1. it would be better to do:

    if files:
    os.system(….)

    I know it's silly, but I tried it in an empty repo and it just hanged waiting for input :)

  2. it would be better to do:

    if files:
    os.system(….)

    I know it's silly, but I tried it in an empty repo and it just hanged waiting for input :)

Leave a Reply

Your email address will not be published. Required fields are marked *