Thanks to Collin Anderson for the suggestion and Tim Graham for reviewing the patch. Backport of 22c6497f99 from master
22c6497f99