localrepo: restore "refactor and improvements to tree functions"
!5642 (merged) refactored functions in the localrepo
package to write trees. Unfortunately, a bug in the code caused downstream failures and had to be reverted.
This bug has been fixed, and a test cases has been added to account for this situation.
This MR restores the commits in !5642 (merged), but the commit 6f2d0e6f has had the bug fixed and the test case added.