How to limit to N newest entries with Hg Log when specifying a Revset?

302 views Asked by At

This question is not a duplicate of hg log - How to get the last 5 log entries? - it is easy to apply a limit. The problem is that the log output, when limited, does not appear to always be ordered descending by log date - the behavior changes with the addition of a revset.

For example, the simple log work "as expected" and it is displays the newest five log entries.

hg log -l5

However, when using a revset the result is the oldest nodes first (as observed without -l); hence the following shows the oldest five entries which is not desired.

hg log -r "user('Me')" -l5

How can can hg log, with a revset, be instructed to order by the log date descending ("as expected") so that the limit has a predictable1 and meaningful effect?


$ hg --version
Mercurial Distributed SCM (version 3.6.1)

1 I don't consider throwing random reverse calls in a revset predictable, but if that is the "best" way..

2

There are 2 answers

2
Reimer Behrends On BEST ANSWER

There are a couple of options you have.

First, you can use reverse() in conjunction with your existing revset, e.g.:

hg log -r 'reverse(user("me"))' -l 5

As a shorthand, you can also use -f or --follow, which – when used in conjunction with -r – will wrap the revision in reverse(...). Example:

hg log -f -r 'user("me")' -l 5

Or you can encode the limit in the changeset, e.g.:

hg log -r 'last(user("me"), 5)'

Note that revset aliases can be useful to avoid having to type out revsets over and over. So, you can put something like this in your .hgrc:

[revsetalias]
lastby($1) = last(user($1), 5)

And then do:

hg log -r 'lastby("me")`
0
user2864740 On

Important addendum answer: do not use reverse blindly for this task. While it will work in many cases, the better/reliable generic solution is to use sort, as in:

hg log -r 'sort(user("me"), "-date")' -l 5

This is because reverse does not guarantee the source set order is well-ordered - as such it may still result in final output that does not meet the requested criteria of 'newest'.

The use of sort above guarantees the behavior as it sorts by the date, descending, and then selects the top 5 per hg log's limit option.

(Otherwise, see Reimer's answer.)