fix: Prevent deletion of non-empty directories

Signed-off-by: Knut Borchers <knut.borchers@gmail.com>
This commit is contained in:
Knut Borchers
2023-02-18 18:02:46 +01:00
parent da03381181
commit bfe350ef4c
3 changed files with 28 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-techdocs-node': patch
---
Fixed bug that prevented deletion of stale files when non-empty directories where tried to be deleted as well.
@@ -158,6 +158,16 @@ describe('getStaleFiles', () => {
expect(staleFiles).toHaveLength(1);
expect(staleFiles).toEqual(expect.arrayContaining(['stale_file.png']));
});
it('should not return directories as stale files if they are parent directories of new files', () => {
const oldFiles = [...defaultFiles, 'default/Component/backstage/foo'];
const newFiles = [
...defaultFiles,
'default/Component/backstage/foo/bar/index.html',
];
const staleFiles = getStaleFiles(newFiles, oldFiles);
expect(staleFiles).toHaveLength(0);
});
});
describe('getCloudPathForLocalPath', () => {
@@ -169,8 +169,21 @@ export const getStaleFiles = (
oldFiles: string[],
): string[] => {
const staleFiles = new Set(oldFiles);
const removedParentDirs = new Set();
newFiles.forEach(newFile => {
staleFiles.delete(newFile);
// We have to traverse through the directory hierarchy of a new file and
// ensure that we won't try to delete one of the parent directories.
let parentDir = newFile.substring(0, newFile.lastIndexOf('/'));
while (
!removedParentDirs.has(parentDir) &&
parentDir.length >= newFile.indexOf('/')
) {
staleFiles.delete(parentDir);
removedParentDirs.add(parentDir);
parentDir = parentDir.substring(0, parentDir.lastIndexOf('/'));
}
});
return Array.from(staleFiles);
};