Skip to content

Commit

Permalink
Fix Switch.removeSync() on files
Browse files Browse the repository at this point in the history
Fixes #82.
  • Loading branch information
TooTallNate committed Jan 24, 2024
1 parent df7b564 commit 977c19f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/weak-poems-design.md
@@ -0,0 +1,5 @@
---
'nxjs-runtime': patch
---

Fix `Switch.removeSync()` on files
33 changes: 33 additions & 0 deletions apps/tests/src/switch.ts
Expand Up @@ -117,4 +117,37 @@ test('`Switch.stat()` rejects when file does not exist', async () => {
assert.ok(err);
});

test('`Switch.removeSync()` removes file', async () => {
const path = 'sdmc:/__nxjs-test.txt';
const uuid = crypto.randomUUID();
Switch.writeFileSync(path, uuid);
const data = Switch.readFileSync(path);
assert.ok(data);
assert.equal(new TextDecoder().decode(data), uuid);

Switch.removeSync(path);
assert.equal(Switch.statSync(path), null);
});

test('`Switch.removeSync()` removes directory', async () => {
const path = 'sdmc:/__nxjs-test';
Switch.mkdirSync(path);
assert.ok(Switch.statSync(path));

Switch.removeSync(path);
assert.equal(Switch.statSync(path), null);
});

test('`Switch.removeSync()` removes nested directory', async () => {
const dir = 'sdmc:/__nested';
const path = `${dir}/another/nxjs-test/file.txt`;
Switch.writeFileSync(path, 'hello world');
assert.ok(Switch.statSync(dir));
assert.ok(Switch.statSync(path));

Switch.removeSync(dir);
assert.equal(Switch.statSync(dir), null);
assert.equal(Switch.statSync(path), null);
});

test.run();
15 changes: 11 additions & 4 deletions source/fs.c
Expand Up @@ -424,8 +424,15 @@ JSValue nx_stat_sync(JSContext *ctx, JSValueConst this_val, int argc, JSValueCon
return statToObject(ctx, &st);
}

int removeDirectory(const char *path)
int removeFileOrDirectory(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
if (S_ISREG(path_stat.st_mode))
{
return unlink(path);
}

DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
Expand Down Expand Up @@ -458,7 +465,7 @@ int removeDirectory(const char *path)
if (!stat(buf, &statbuf))
{
if (S_ISDIR(statbuf.st_mode))
r2 = removeDirectory(buf);
r2 = removeFileOrDirectory(buf);
else
r2 = unlink(buf);
}
Expand All @@ -483,7 +490,7 @@ int removeDirectory(const char *path)
void nx_remove_do(nx_work_t *req)
{
nx_fs_remove_async_t *data = (nx_fs_remove_async_t *)req->data;
if (removeDirectory(data->filename) != 0)
if (removeFileOrDirectory(data->filename) != 0)
{
data->err = errno;
}
Expand Down Expand Up @@ -518,7 +525,7 @@ JSValue nx_remove_sync(JSContext *ctx, JSValueConst this_val, int argc, JSValueC
const char *path = JS_ToCString(ctx, argv[0]);
if (!path)
return JS_EXCEPTION;
int result = removeDirectory(path);
int result = removeFileOrDirectory(path);
JS_FreeCString(ctx, path);
if (result != 0)
{
Expand Down

0 comments on commit 977c19f

Please sign in to comment.