Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(): Add recursive option for rmdir #1781

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ public void rmdir(PluginCall call) {
saveCall(call);
String path = call.getString("path");
String directory = getDirectoryParameter(call);
Boolean recursive = call.getBoolean("recursive", false);

File fileObject = getFileObject(path, directory);

Expand All @@ -366,7 +367,18 @@ public void rmdir(PluginCall call) {
return;
}

boolean deleted = fileObject.delete();
if (fileObject.isDirectory() && fileObject.listFiles().length != 0 && !recursive) {
call.error("Directory is not empty");
return;
}

boolean deleted = false;

try {
deleteRecursively(fileObject);
deleted = true;
} catch (IOException ignored) {
}

if(deleted == false) {
call.error("Unable to delete directory, unknown reason");
Expand Down Expand Up @@ -439,6 +451,25 @@ public void stat(PluginCall call) {
}
}

/**
* Helper function to recursively delete a directory
*
* @param file The file or directory to recursively delete
* @throws IOException
*/
private static void deleteRecursively(File file) throws IOException {
if (file.isFile()) {
file.delete();
return;
}

for (File f : file.listFiles()) {
deleteRecursively(f);
}

file.delete();
}

/**
* Helper function to recursively copy a directory structure (or just a file)
*
Expand Down
4 changes: 4 additions & 0 deletions core/src/core-plugin-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,10 @@ export interface RmdirOptions {
* The FilesystemDirectory to remove the directory from
*/
directory?: FilesystemDirectory;
/**
* Whether to recursively remove the contents of the directory (defaults to false)
*/
recursive?: boolean;
}

export interface ReaddirOptions {
Expand Down
29 changes: 23 additions & 6 deletions core/src/web/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,16 +278,33 @@ export class FilesystemPluginWeb extends WebPlugin implements FilesystemPlugin {
* @param options the options for the directory remove
*/
async rmdir(options: RmdirOptions): Promise<RmdirResult> {
const path: string = this.getPath(options.directory, options.path);
let {path, directory, recursive} = options;
const fullPath: string = this.getPath(directory, path);

let entry = await this.dbRequest('get', [fullPath]) as EntryObj;

let entry = await this.dbRequest('get', [path]) as EntryObj;
if (entry === undefined)
throw Error('Folder does not exist.');
let entries = await this.dbIndexRequest('by_folder', 'getAllKeys', [IDBKeyRange.only(path)]);
if (entries.length !== 0)
throw Error('Folder is not empty.');

await this.dbRequest('delete', [path]);
if (entry.type !== 'directory')
throw Error('Requested path is not a directory');

let readDirResult = await this.readdir({path, directory});

if (readDirResult.files.length !== 0 && !recursive)
throw Error('Folder is not empty');

for (const entry of readDirResult.files) {
let entryPath = `${path}/${entry}`;
let entryObj = await this.stat({path: entryPath, directory});
if (entryObj.type === 'file') {
await this.deleteFile({path: entryPath, directory});
} else {
await this.rmdir({path: entryPath, directory, recursive});
}
}

await this.dbRequest('delete', [fullPath]);
return {};
}

Expand Down
57 changes: 45 additions & 12 deletions electron/src/electron/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,19 +120,46 @@ export class FilesystemPluginElectron extends WebPlugin implements FilesystemPlu
}

rmdir(options: RmdirOptions): Promise<RmdirResult> {
return new Promise((resolve, reject) => {
if(Object.keys(this.fileLocations).indexOf(options.directory) === -1)
reject(`${options.directory} is currently not supported in the Electron implementation.`);
let lookupPath = this.fileLocations[options.directory] + options.path;
this.NodeFS.rmdir(lookupPath, (err:any) => {
if(err) {
reject(err);
return;
}
let {path, directory, recursive} = options;

if (Object.keys(this.fileLocations).indexOf(directory) === -1)
return Promise.reject(`${directory} is currently not supported in the Electron implementation.`);

return this.stat({path, directory})
.then((stat) => {
if (stat.type === 'directory') {
return this.readdir({path, directory})
.then((readDirResult) => {
if (readDirResult.files.length !== 0 && !recursive) {
return Promise.reject(`${path} is not empty.`);
}

resolve();
if (!readDirResult.files.length) {
return new Promise((resolve, reject) => {
let lookupPath = this.fileLocations[directory] + path;

this.NodeFS.rmdir(lookupPath, (err: any) => {
if (err) {
reject(err);
return;
}

resolve();
});
});
} else {
return Promise.all(readDirResult.files.map((f) => {
return this.rmdir({path: this.Path.join(path, f), directory, recursive});
}))
.then(() => {
return this.rmdir({path, directory, recursive});
});
}
});
} else {
return this.deleteFile({path, directory});
}
});
});
}

readdir(options: ReaddirOptions): Promise<ReaddirResult> {
Expand Down Expand Up @@ -171,7 +198,13 @@ export class FilesystemPluginElectron extends WebPlugin implements FilesystemPlu
return;
}

resolve({type: 'Not Available', size: stats.size, ctime: stats.ctimeMs, mtime: stats.mtimeMs, uri: lookupPath});
resolve({
type: (stats.isDirectory() ? 'directory' : (stats.isFile() ? 'file' : 'Not available')),
size: stats.size,
ctime: stats.ctimeMs,
mtime: stats.mtimeMs,
uri: lookupPath
});
});
});
}
Expand Down
12 changes: 12 additions & 0 deletions ios/Capacitor/Capacitor/Plugins/Filesystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,18 @@ public class CAPFilesystemPlugin : CAPPlugin {
return
}

let recursiveOption = call.get("recursive", Bool.self, false)!

do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: fileUrl, includingPropertiesForKeys: nil, options: [])
if (directoryContents.count != 0 && !recursiveOption) {
handleError(call, "Folder is not empty")
return
}
} catch {
handleError(call, error.localizedDescription, error)
}

do {
try FileManager.default.removeItem(at: fileUrl)
call.success()
Expand Down
3 changes: 2 additions & 1 deletion site/docs-md/apis/filesystem/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ async rmdir() {
try {
let ret = await Filesystem.rmdir({
path: 'secrets',
directory: FilesystemDirectory.Documents
directory: FilesystemDirectory.Documents,
recursive: false,
});
} catch(e) {
console.error('Unable to remove directory', e);
Expand Down