Seems like the puppet guys have similar code: https://github.com/puppetlabs/puppet/pull/1778/files