Copied from the official mercurial repo