Created
January 27, 2011 00:43
-
-
Save conradchu/797841 to your computer and use it in GitHub Desktop.
Here's a way I parse through keys in an S3 bucket, calculating depth based on number of /'s in the key. I then parse and throw folders/files that are too deep and show only the folder/file entries at the current level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def entries(dir = '') | |
entries = [] | |
# Depth of the directory path | |
dir_depth = dir.count('/') | |
@bucket.keys(:prefix => path).each do |entry| | |
# Entries cannot end with ~ (ascii 126) or starts with # or . (35 and 46 respectively) | |
if entry.name[-1] != 126 && entry.name[0] != 35 && entry.name[0] != 46 && entry.name != path | |
# If is a subdirectory (entries that are deeper than the current path must only be directories) | |
if (entry.depth == dir_depth + 1 && entry.is_folder?) || entry.depth == dir_depth | |
entries << entry | |
end | |
end | |
end | |
end | |
module RightAws | |
class S3 | |
class Bucket | |
def common_prefixes(prefix, delimiter = '/') | |
common_prefixes = [] | |
@s3.interface.incrementally_list_bucket(@name, { 'prefix' => prefix, 'delimiter' => delimiter }) do |thislist| | |
common_prefixes += thislist[:common_prefixes] | |
end | |
common_prefixes | |
end | |
end | |
class Key | |
# Is this key a folder | |
def is_folder? | |
self.name[-1] == 47 | |
end | |
# Return the depth of the key | |
def depth | |
self.name.count('/') | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment