Factor out duplicated code

[ci skip]