Refactor to reduce number of loops

Only build the missing_keys array once we have detected that there
actually are missing keys by moving the check to be part of the block
that performs the path substitution.
(cherry picked from commit 1a58ac60d92110cc9a83c976ac1fbd7bfd071966)