Prevent prefix based conflicts when renaming

Renaming file "foo" should not affect file "foobar/baz" even though "foo" is a prefix of "foobar".

Best merged after #2912 since it can't really be tested without it. Though the commit is included here, too. Please let me know if I should create a pull request with just the last commit.