blob: 4c3229b4e53c658f7942735cc974883b19d04651 [file] [log] [blame]
Attila Fazekasa23f5002012-10-23 19:32:45 +02001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
3# Copyright 2012 OpenStack, LLC
4# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17
Attila Fazekasa23f5002012-10-23 19:32:45 +020018from contextlib import closing
Matthew Treinisha83a16e2012-12-07 13:44:02 -050019import logging
Attila Fazekasa23f5002012-10-23 19:32:45 +020020import os
21import re
Attila Fazekasa23f5002012-10-23 19:32:45 +020022
Matthew Treinisha83a16e2012-12-07 13:44:02 -050023import boto
24from boto.s3.key import Key
Attila Fazekasa23f5002012-10-23 19:32:45 +020025
26LOG = logging.getLogger(__name__)
27
28
29def s3_upload_dir(bucket, path, prefix="", connection_data=None):
30 if isinstance(bucket, basestring):
31 with closing(boto.connect_s3(**connection_data)) as conn:
32 bucket = conn.lookup(bucket)
33 for root, dirs, files in os.walk(path):
34 for fil in files:
35 with closing(Key(bucket)) as key:
36 source = root + os.sep + fil
37 target = re.sub("^" + re.escape(path) + "?/", prefix, source)
38 if os.sep != '/':
39 target = re.sub(re.escape(os.sep), '/', target)
40 key.key = target
41 LOG.info("Uploading %s to %s/%s", source, bucket.name, target)
42 key.set_contents_from_filename(source)