diff -r 1e0516ee4cb9 -r b20d04641c0f hgext3rd/evolve/headchecking.py --- a/hgext3rd/evolve/headchecking.py Mon Apr 06 05:08:23 2020 +0200 +++ b/hgext3rd/evolve/headchecking.py Wed Mar 11 23:56:11 2020 +0100 @@ -4,10 +4,15 @@ from mercurial import ( discovery, + error, extensions, phases, + scmutil, + util, ) +from mercurial.i18n import _ + from . import ( compat, @@ -20,6 +25,7 @@ @eh.uisetup def uisetup(ui): extensions.wrapfunction(discovery, '_postprocessobsolete', _postprocessobsolete) + extensions.wrapfunction(scmutil, 'enforcesinglehead', enforcesinglehead) def branchinfo(pushop, repo, node): return repo[node].branch() @@ -111,3 +117,71 @@ discarded.add(nh) newhs |= unknownheads return newhs, discarded + +def _get_branch_name(ctx): + # make it easy for extension with the branch logic there + branch = ctx.branch() + if util.safehasattr(ctx, 'topic'): + topic = ctx.topic() + if topic: + branch = "%s:%s" % (branch, topic) + return branch + +def _filter_obsolete_heads(repo, heads): + """filter heads to return non-obsolete ones + + Given a list of heads (on the same named branch) return a new list of heads + where the obsolete part have been skimmed out. + """ + new_heads = [] + old_heads = heads[:] + while old_heads: + rh = old_heads.pop() + ctx = repo[rh] + current_name = _get_branch_name(ctx) + # run this check early to skip the evaluation of the whole branch + if not ctx.obsolete(): + new_heads.append(rh) + continue + + # Get all revs/nodes on the branch exclusive to this head + # (already filtered heads are "ignored")) + sections_revs = repo.revs( + b'only(%d, (%ld+%ld))', rh, old_heads, new_heads, + ) + keep_revs = [] + for r in sections_revs: + ctx = repo[r] + if ctx.obsolete(): + continue + if _get_branch_name(ctx) != current_name: + continue + keep_revs.append(r) + for h in repo.revs(b'heads(%ld and (::%ld))', sections_revs, keep_revs): + new_heads.append(h) + new_heads.sort() + return new_heads + +def enforcesinglehead(orig, repo, tr, desc, accountclosed=False): + """check that no named branch has multiple heads""" + nodesummaries = scmutil.nodesummaries + if desc in (b'strip', b'repair'): + # skip the logic during strip + return + visible = repo.filtered(b'visible') + # possible improvement: we could restrict the check to affected branch + bm = visible.branchmap() + cl = repo.changelog + to_rev = cl.rev + to_node = cl.node + for name in bm: + all_heads = bm.branchheads(name, closed=accountclosed) + all_heads = [to_rev(n) for n in all_heads] + heads = _filter_obsolete_heads(repo, all_heads) + heads = [to_node(r) for r in heads] + if len(heads) > 1: + msg = _(b'rejecting multiple heads on branch "%s"') + msg %= name + hint = _(b'%d heads: %s') + hint %= (len(heads), nodesummaries(repo, heads)) + raise error.Abort(msg, hint=hint)