Skip to content

Commit

Permalink
fix(updateIndex): prevent removing directories (isomorphic-git#1521)
Browse files Browse the repository at this point in the history
  • Loading branch information
SamVerschueren authored Mar 21, 2022
1 parent 942ed52 commit 2e09b91
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 4 deletions.
70 changes: 70 additions & 0 deletions __tests__/test-updateIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,4 +265,74 @@ describe('updateIndex', () => {
}
`)
})

it('should throw if we try to remove a directory', async () => {
// Setup
const { fs, dir } = await makeFixture('test-empty')
await fs.mkdir(path.join(dir, 'hello-world'))
await fs.write(path.join(dir, 'hello-world/a'), 'a')
await add({
fs,
dir,
filepath: 'hello-world/a',
})
// Test
let error = null
try {
await updateIndex({
fs,
dir,
remove: true,
filepath: 'hello-world',
})
} catch (e) {
error = e
}
expect(error).not.toBeNull()
expect(error.caller).toEqual('git.updateIndex')
error = error.toJSON()
delete error.stack
expect(error).toMatchInlineSnapshot(`
Object {
"caller": "git.updateIndex",
"code": "InvalidFilepathError",
"data": Object {
"reason": "directory",
},
"message": "\\"filepath\\" should not be a directory.",
}
`)
})

it('should not throw if we force remove a directory', async () => {
// Setup
const { fs, dir } = await makeFixture('test-empty')
await fs.mkdir(path.join(dir, 'hello-world'))
await fs.write(path.join(dir, 'hello-world/a'), 'a')
await add({
fs,
dir,
filepath: 'hello-world/a',
})
// Test
let fileStatus = await status({
fs,
dir,
filepath: 'hello-world/a',
})
expect(fileStatus).toBe('added')
await updateIndex({
fs,
dir,
remove: true,
force: true,
filepath: 'hello-world',
})
fileStatus = await status({
fs,
dir,
filepath: 'hello-world/a',
})
expect(fileStatus).toBe('added')
})
})
15 changes: 11 additions & 4 deletions src/api/updateIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,22 @@ export async function updateIndex({
fileStats = await fs.lstat(join(dir, filepath))

if (fileStats) {
if (fileStats.isDirectory()) {
// Removing directories should not work
throw new InvalidFilepathError('directory')
}

// Do nothing if we don't force and the file still exists in the workdir
return
}
}

// Remove the file from the index if it's forced or the file does not exist
index.delete({
filepath,
})
// Directories are not allowed, so we make sure the provided filepath exists in the index
if (index.has({ filepath })) {
index.delete({
filepath,
})
}
}
)
}
Expand Down

0 comments on commit 2e09b91

Please sign in to comment.