Skip to content

Commit

Permalink
feat: implement the empty operation (#12)
Browse files Browse the repository at this point in the history
This will implement the `empty` action available in the console(`rm
--recursive` in the cli). I want the behavior to be drawn from the
behavior of the cli; the function will return a list of keys that
were deleted. I'm also thinking about adding a `quiet` option that
simply returns the keys that failed to delete, but probably not for
the first version.
  • Loading branch information
wperron committed Oct 4, 2020
1 parent 8bf10d5 commit cf7f063
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export function sha256Hex(data: string | Uint8Array): string {
}
export { default as parseXML } from "https://raw.githubusercontent.com/nekobato/deno-xml-parser/0bc4c2bd2f5fad36d274279978ca57eec57c680c/index.ts";
export { decode as decodeXMLEntities } from "https://deno.land/x/[email protected]/lib/xml-entities.js";
export { pooledMap } from "https://deno.land/[email protected]/async/pool.ts";
23 changes: 23 additions & 0 deletions src/bucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
AWSSignerV4,
decodeXMLEntities,
parseXML,
pooledMap,
sha256Hex,
} from "../deps.ts";
import type { S3Config } from "./client.ts";
Expand Down Expand Up @@ -486,6 +487,28 @@ export class S3Bucket {
deleteMarker: resp.headers.get("x-amz-delete-marker") === "true",
};
}

/**
* Deletes all objects in the bucket recursively. Returns a list of deleted keys.
*/
async empty(): Promise<string[]> {
const deleted: string[] = [];
for await (
let k of pooledMap(
50,
this.listAllObjects({ batchSize: 1000 }),
async (o) => {
if (o.key) {
await this.deleteObject(o.key!);
return o.key!;
}
},
)
) {
deleted.push(k!);
}
return deleted;
}
}

function encodeURIS3(input: string): string {
Expand Down
29 changes: 29 additions & 0 deletions src/bucket_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,32 @@ Deno.test({
}
},
});

Deno.test({
name: "empty bucket",
async fn() {
// setup
const content = encoder.encode("Test1");
const keys = [
"fooz",
"bar",
"foo/sub2",
"foo/sub3/subsub",
"baz",
"fruits/blueberry",
"fruits/banana",
"fruits/strawberry",
"fruits/apple",
"fruits/orange",
];

for (let k of keys) {
await bucket.putObject(k, content, { contentType: "text/plain" });
}

const deleted = await bucket.empty();
deleted.sort();
keys.sort();
assertEquals(deleted, keys);
},
});

0 comments on commit cf7f063

Please sign in to comment.