Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(19)

Side by Side Diff: third_party/gsutil/gslib/bucket_listing_ref.py

Issue 12042069: Scripts to download files from google storage based on sha1 sums (Closed) Base URL: https://chromium.googlesource.com/chromium/tools/depot_tools.git@master
Patch Set: Removed gsutil/tests and gsutil/docs Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2012 Google Inc.
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the
5 # "Software"), to deal in the Software without restriction, including
6 # without limitation the rights to use, copy, modify, merge, publish, dis-
7 # tribute, sublicense, and/or sell copies of the Software, and to permit
8 # persons to whom the Software is furnished to do so, subject to the fol-
9 # lowing conditions:
10 #
11 # The above copyright notice and this permission notice shall be included
12 # in all copies or substantial portions of the Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16 # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17 # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 # IN THE SOFTWARE.
21
22 import time
23
24
25 class BucketListingRef(object):
26 """
27 Container that holds a reference to one result from a bucket listing, allowing
28 polymorphic iteration over wildcard-iterated URIs, Keys, or Prefixes. At a
29 minimum, every reference contains a StorageUri. If the reference came from a
30 bucket listing (as opposed to a manually instantiated ref that might populate
31 only the StorageUri), it will additionally contain either a Key or a Prefix,
32 depending on whether it was a reference to an object or was just a prefix of a
33 path (i.e., bucket subdirectory). The latter happens when the bucket was
34 listed using delimiter='/'.
35
36 Note that Keys are shallow-populated, based on the contents extracted from
37 parsing a bucket listing. This includes name, length, and other fields
38 (basically, the info listed by gsutil ls -l), but does not include information
39 like ACL and location (which require separate server requests, which is why
40 there's a separate gsutil ls -L option to get this more detailed info).
41 """
42
43 def __init__(self, uri, key=None, prefix=None, headers=None):
44 """Instantiate BucketListingRef from uri and (if available) key or prefix.
45
46 Args:
47 uri: StorageUri for the object (required).
48 key: Key for the object, or None if not available.
49 prefix: Prefix for the subdir, or None if not available.
50 headers: Dictionary containing optional HTTP headers to pass to boto
51 (which happens when GetKey() is called on an BucketListingRef which
52 has no constructor-populated Key), or None if not available.
53
54 At most one of key and prefix can be populated.
55 """
56 assert uri is not None
57 # At most one of key or prefix may be specified.
58 assert key is None or prefix is None
59 self.uri = uri
60 self.key = key
61 self.prefix = prefix
62 self.headers = headers or {}
63
64 def GetUri(self):
65 """Get URI form of listed URI.
66
67 Returns:
68 StorageUri.
69 """
70 return self.uri
71
72 def GetUriString(self):
73 """Get string URI form of listed URI.
74
75 Returns:
76 String.
77 """
78 return self.uri.uri
79
80 def NamesBucket(self):
81 """Determines if this BucketListingRef names a bucket.
82
83 Returns:
84 bool indicator.
85 """
86 return self.key is None and self.prefix is None and self.uri.names_bucket()
87
88 def GetRStrippedUriString(self):
89 """Get string URI form of listed URI, stripped of any right trailing delims.
90
91 Returns:
92 String.
93 """
94 return self.GetUriString().rstrip('/')
95
96 def HasKey(self):
97 """Return bool indicator of whether this BucketListingRef has a Key."""
98 return bool(self.key)
99
100 def HasPrefix(self):
101 """Return bool indicator of whether this BucketListingRef has a Prefix."""
102 return bool(self.prefix)
103
104 def GetKey(self):
105 """Get Key form of listed URI.
106
107 Returns:
108 Subclass of boto.s3.key.Key.
109
110 Raises:
111 BucketListingRefException: for bucket-only uri.
112 """
113 # For gsutil ls -l gs://bucket self.key will be populated from (boto)
114 # parsing the bucket listing. But as noted and handled below there are
115 # cases where self.key isn't populated.
116 if not self.key:
117 if not self.uri.names_object():
118 raise BucketListingRefException(
119 'Attempt to call GetKey() on Key-less BucketListingRef (uri=%s) ' %
120 self.uri)
121 # This case happens when we do gsutil ls -l on a object name-ful
122 # StorageUri with no object-name wildcard. Since the ls command
123 # implementation only reads bucket info we need to read the object
124 # for this case.
125 self.key = self.uri.get_key(validate=False, headers=self.headers)
126 # When we retrieve the object this way its last_modified timestamp
127 # is formatted in RFC 1123 format, which is different from when we
128 # retrieve from the bucket listing (which uses ISO 8601 format), so
129 # convert so we consistently return ISO 8601 format.
130 tuple_time = (time.strptime(self.key.last_modified,
131 '%a, %d %b %Y %H:%M:%S %Z'))
132 self.key.last_modified = time.strftime('%Y-%m-%dT%H:%M:%S', tuple_time)
133 return self.key
134
135 def GetPrefix(self):
136 """Get Prefix form of listed URI.
137
138 Returns:
139 boto.s3.prefix.Prefix.
140
141 Raises:
142 BucketListingRefException: if this object has no Prefix.
143 """
144 if not self.prefix:
145 raise BucketListingRefException(
146 'Attempt to call GetPrefix() on Prefix-less BucketListingRef '
147 '(uri=%s)' % self.uri)
148 return self.prefix
149
150 def __repr__(self):
151 """Returns string representation of BucketListingRef."""
152 return 'BucketListingRef(%s, HasKey=%s, HasPrefix=%s)' % (
153 self.uri, self.HasKey(), self.HasPrefix())
154
155
156 class BucketListingRefException(StandardError):
157 """Exception thrown for invalid BucketListingRef requests."""
158
159 def __init__(self, reason):
160 StandardError.__init__(self)
161 self.reason = reason
162
163 def __repr__(self):
164 return 'BucketListingRefException: %s' % self.reason
165
166 def __str__(self):
167 return 'BucketListingRefException: %s' % self.reason
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698