Skip to content

Instantly share code, notes, and snippets.

@conradchu
Created January 27, 2011 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conradchu/797841 to your computer and use it in GitHub Desktop.
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
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