File size: 16,648 Bytes
5980447
1
2
{"repo": "WhoopInc/mkwheelhouse", "pull_number": 7, "instance_id": "WhoopInc__mkwheelhouse-7", "issue_numbers": "", "base_commit": "941f30c4479816c4ddff350f8bf5e08635d11d2d", "patch": "diff --git a/mkwheelhouse.py b/mkwheelhouse.py\n--- a/mkwheelhouse.py\n+++ b/mkwheelhouse.py\n@@ -1,94 +1,94 @@\n #!/usr/bin/env python\n \n from __future__ import print_function\n+from __future__ import unicode_literals\n \n import argparse\n import glob\n+import json\n import mimetypes\n import os\n import subprocess\n import tempfile\n \n-import botocore.session\n+import boto\n+import boto.s3.connection\n+import shutil\n import yattag\n \n \n-class Bucket:\n+class Bucket(object):\n     def __init__(self, name):\n         self.name = name\n-        self.s3_service = botocore.session.get_session().get_service('s3')\n-\n-    def region(self):\n-        if not hasattr(self, '_region'):\n-            default_endpoint = self.s3_service.get_endpoint()\n-            op = self.s3_service.get_operation('GetBucketLocation')\n-            http_response, response_data = op.call(default_endpoint,\n-                                                   bucket=self.name)\n-            self._region = response_data['LocationConstraint']\n-        return self._region or 'us-east-1'\n-\n-    def endpoint(self):\n-        return self.s3_service.get_endpoint(self.region())\n-\n-    def remote_url(self):\n-        return 's3://{0}'.format(self.name)\n-\n-    def resource_url(self, resource):\n-        return os.path.join(self.endpoint().host, self.name, resource)\n+        # Boto currently can't handle names with dots unless the region\n+        # is specified explicitly.\n+        # See: https://github.com/boto/boto/issues/2836\n+        self.region = self._get_region()\n+        self.s3 = boto.s3.connect_to_region(\n+            region_name=self.region,\n+            calling_format=boto.s3.connection.OrdinaryCallingFormat())\n+        self.bucket = self.s3.get_bucket(name)\n+\n+    def _get_region(self):\n+        # S3, for what appears to be backwards-compatibility\n+        # reasons, maintains a distinction between location\n+        # constraints and region endpoints. Newer regions have\n+        # equivalent regions and location constraints, so we\n+        # hardcode the non-equivalent regions here with hopefully no\n+        # automatic support future S3 regions.\n+        #\n+        # Note also that someday, Boto should handle this for us\n+        # instead of the AWS command line tools.\n+        process = subprocess.Popen([\n+            'aws', 's3api', 'get-bucket-location',\n+            '--bucket', self.name], stdout=subprocess.PIPE)\n+        stdout, _ = process.communicate()\n+        location = json.loads(stdout.decode())['LocationConstraint']\n+        if not location:\n+            return 'us-east-1'\n+        elif location == 'EU':\n+            return 'eu-west-1'\n+        else:\n+            return location\n+\n+    def generate_url(self, key):\n+        if not isinstance(key, boto.s3.key.Key):\n+            key = boto.s3.key.Key(bucket=self.bucket, name=key)\n+\n+        return key.generate_url(expires_in=0, query_auth=False)\n \n     def sync(self, local_dir):\n         return subprocess.check_call([\n             'aws', 's3', 'sync',\n-            local_dir, self.remote_url(),\n-            '--region', self.region()])\n+            local_dir, 's3://{0}'.format(self.bucket.name),\n+            '--region', self.region])\n \n     def put(self, body, key):\n-        args = [\n-            'aws', 's3api', 'put-object',\n-            '--bucket', self.name,\n-            '--region', self.region(),\n-            '--key', key\n-        ]\n-\n-        content_type = mimetypes.guess_type(key)[0]\n-        if content_type:\n-            args += ['--content-type', content_type]\n-\n-        with tempfile.NamedTemporaryFile() as f:\n-            f.write(body.encode('utf-8'))\n-            f.flush()\n-            args += ['--body', f.name]\n-            return subprocess.check_call(args)\n-\n-    def wheels(self):\n-        op = self.s3_service.get_operation('ListObjects')\n-        http_response, response_data = op.call(self.endpoint(),\n-                                               bucket=self.name)\n+        key = boto.s3.key.Key(bucket=self.bucket, name=key)\n \n-        keys = [obj['Key'] for obj in response_data['Contents']]\n-        keys = [key for key in keys if key.endswith('.whl')]\n+        content_type = mimetypes.guess_type(key.name)[0]\n+        if content_type:\n+            key.content_type = content_type\n \n-        wheels = []\n-        for key in keys:\n-            url = self.resource_url(key)\n-            wheels.append((key, url))\n+        key.set_contents_from_string(body, replace=True)\n \n-        return wheels\n+    def list_wheels(self):\n+        return [key for key in self.bucket.list() if key.name.endswith('.whl')]\n \n-    def index(self):\n+    def make_index(self):\n         doc, tag, text = yattag.Doc().tagtext()\n         with tag('html'):\n-            for name, url in self.wheels():\n-                with tag('a', href=url):\n-                    text(name)\n+            for key in self.list_wheels():\n+                with tag('a', href=self.generate_url(key)):\n+                    text(key.name)\n                 doc.stag('br')\n \n         return doc.getvalue()\n \n \n-def build_wheels(packages, index_url, requirements=None):\n-    packages = packages or []\n+def build_wheels(packages, index_url, requirements, exclusions):\n     temp_dir = tempfile.mkdtemp(prefix='mkwheelhouse-')\n+\n     args = [\n         'pip', 'wheel',\n         '--wheel-dir', temp_dir,\n@@ -96,10 +96,16 @@ def build_wheels(packages, index_url, requirements=None):\n     ]\n \n     for requirement in requirements:\n-        args += ['-r', requirement]\n+        args += ['--requirement', requirement]\n \n     args += packages\n     subprocess.check_call(args)\n+\n+    for exclusion in exclusions:\n+        matches = glob.glob(os.path.join(temp_dir, exclusion))\n+        for match in matches:\n+            os.remove(match)\n+\n     return temp_dir\n \n \n@@ -113,7 +119,7 @@ def main():\n                         metavar='WHEEL_FILENAME',\n                         help='Wheels to exclude from upload')\n     parser.add_argument('bucket')\n-    parser.add_argument('package', nargs='*')\n+    parser.add_argument('package', nargs='*', default=[])\n \n     args = parser.parse_args()\n \n@@ -121,17 +127,13 @@ def main():\n         parser.error('specify at least one requirements file or package')\n \n     bucket = Bucket(args.bucket)\n-    index_url = bucket.resource_url('index.html')\n-\n-    build_dir = build_wheels(args.package, index_url, args.requirement)\n-\n-    # Remove exclusions from the build_dir -e/--exclude\n-    for exclusion in args.exclude:\n-        matches = glob.glob(os.path.join(build_dir, exclusion))\n-        map(os.remove, matches)\n+    index_url = bucket.generate_url('index.html')\n \n+    build_dir = build_wheels(args.package, index_url, args.requirement,\n+                             args.exclude)\n     bucket.sync(build_dir)\n-    bucket.put(bucket.index(), key='index.html')\n+    bucket.put(bucket.make_index(), key='index.html')\n+    shutil.rmtree(build_dir)\n \n     print('Index written to:', index_url)\n \ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -4,6 +4,7 @@\n \n install_requires = [\n     'awscli >= 1.3.6',\n+    'boto >= 2.38.0',\n     'yattag >= 0.9.2',\n     'wheel >= 0.23.0',\n     'pip >= 1.5.4',\n@@ -21,13 +22,18 @@\n     url='https://github.com/WhoopInc/mkwheelhouse',\n     description='Amazon S3 wheelhouse generator',\n     classifiers=[\n-      'License :: OSI Approved :: MIT License',\n-      'Development Status :: 4 - Beta',\n-      'Environment :: Console',\n-      'Intended Audience :: Developers',\n-      'Topic :: Software Development :: Build Tools'\n+        'License :: OSI Approved :: MIT License',\n+        'Development Status :: 4 - Beta',\n+        'Environment :: Console',\n+        'Intended Audience :: Developers',\n+        'Topic :: Software Development :: Build Tools'\n     ],\n     install_requires=install_requires,\n+    extras_require={\n+        'tests': [\n+            'pre-commit'\n+        ]\n+    },\n     entry_points={\n         'console_scripts': [\n             'mkwheelhouse=mkwheelhouse:main'\n", "test_patch": "diff --git a/TESTING.rst b/TESTING.rst\nnew file mode 100644\n--- /dev/null\n+++ b/TESTING.rst\n@@ -0,0 +1,41 @@\n+Testing\n+=======\n+\n+No unit testing, since the project is so small. But a full suite of\n+acceptance tests that run using `Bats: Bash Automated Testing\n+System <https://github.com/sstephenson/bats>`_!\n+\n+See `the .travis.yml CI configuration <.travis.yml>`_ for a working\n+example.\n+\n+Environment variables\n+---------------------\n+\n+You'll need to export the below. Recommended values included when not\n+sensitive.\n+\n+.. code:: bash\n+\n+    # AWS credentials with permissions to create S3 buckets\n+    export AWS_ACCESS_KEY_ID=\n+    export AWS_SECRET_ACCESS_KEY=\n+\n+    # Bucket names, one for the US Standard region and one for\n+    # a non-US Standard region to test endpoint logic.\n+    export MKWHEELHOUSE_BUCKET_STANDARD=\"$USER.mkwheelhouse.com\"\n+    export MKWHEELHOUSE_BUCKET_NONSTANDARD=\"$USER.eu.mkwheelhouse.com\"\n+\n+Running tests\n+-------------\n+\n+You'll need `Bats <https://github.com/sstephenson/bats>`_ installed!\n+Then:\n+\n+.. code:: bash\n+\n+    # export env vars as described\n+    $ python setup.py develop\n+    $ test/fixtures.py create\n+    $ bats test/test.bats\n+    # hack hack hack\n+    $ test/fixtures.py delete\ndiff --git a/test/fixtures.py b/test/fixtures.py\nnew file mode 100755\n--- /dev/null\n+++ b/test/fixtures.py\n@@ -0,0 +1,53 @@\n+#!/usr/bin/env python\n+\n+import json\n+import os\n+import sys\n+import traceback\n+\n+import boto\n+from boto.s3.connection import Location, OrdinaryCallingFormat\n+\n+BUCKET_POLICY_PUBLIC = json.dumps({\n+    'Version': '2008-10-17',\n+    'Statement': [{\n+        'Sid': 'AllowPublicRead',\n+        'Effect': 'Allow',\n+        'Principal': {'AWS': '*'},\n+        'Action': ['s3:GetObject'],\n+        'Resource': ['arn:aws:s3:::%s/*']\n+    }]\n+})\n+\n+if len(sys.argv) != 2 or sys.argv[1] not in ['create', 'delete']:\n+    sys.exit('usage: {0} [create|delete]'.format(sys.argv[0]))\n+\n+failed = False\n+\n+# We have to specify both the desired region and location or API\n+# requests will fail in subtle ways and undocumented ways: SSL errors,\n+# missing location constraints, etc.\n+connections = [\n+    (os.environ['MKWHEELHOUSE_BUCKET_NONSTANDARD'], 'eu-west-1', Location.EU),\n+    (os.environ['MKWHEELHOUSE_BUCKET_STANDARD'], 'us-east-1', Location.DEFAULT)\n+]\n+\n+for bucket_name, region, location in connections:\n+    s3 = boto.s3.connect_to_region(region,\n+                                   calling_format=OrdinaryCallingFormat())\n+    if sys.argv[1] == 'create':\n+        bucket = s3.create_bucket(bucket_name, location=location)\n+        bucket.set_policy(BUCKET_POLICY_PUBLIC % bucket_name)\n+    else:\n+        try:\n+            bucket = s3.get_bucket(bucket_name)\n+            bucket.delete_keys([key.name for key in bucket.list()])\n+            bucket.delete()\n+        except boto.exception.S3ResponseError:\n+            traceback.print_exc()\n+            # Don't exit just yet. We may still be able to clean up the\n+            # other buckets.\n+            failed = True\n+            continue\n+\n+sys.exit(failed)\ndiff --git a/test/requirements/default.txt b/test/requirements/default.txt\nnew file mode 100644\n--- /dev/null\n+++ b/test/requirements/default.txt\n@@ -0,0 +1 @@\n+pytsdb==0.2.1\ndiff --git a/test/requirements/exclusions.txt b/test/requirements/exclusions.txt\nnew file mode 100644\n--- /dev/null\n+++ b/test/requirements/exclusions.txt\n@@ -0,0 +1 @@\n+unittest2==1.0.1\ndiff --git a/test/test.bats b/test/test.bats\nnew file mode 100644\n--- /dev/null\n+++ b/test/test.bats\n@@ -0,0 +1,134 @@\n+#!/usr/bin/env bats\n+\n+missing_vars=()\n+\n+require_var() {\n+  [[ \"${!1}\" ]] || missing_vars+=(\"$1\")\n+}\n+\n+require_var MKWHEELHOUSE_BUCKET_STANDARD\n+require_var MKWHEELHOUSE_BUCKET_NONSTANDARD\n+\n+if [[ ${#missing_vars[*]} -gt 0 ]]; then\n+  echo \"Missing required environment variables:\"\n+  printf '    %s\\n' \"${missing_vars[@]}\"\n+  exit 1\n+fi\n+\n+@test \"standard: packages only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" six\n+}\n+\n+@test \"standard: -r only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" \\\n+    -r \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"standard: --requirement only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"standard: --requirement and package\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"standard: -e\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/exclusions.txt\" \\\n+    -e unittest2-1.0.1-py2.py3-none-any.whl\n+}\n+\n+@test \"standard: --exclude\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/exclusions.txt\" \\\n+    --exclude unittest2-1.0.1-py2.py3-none-any.whl\n+}\n+\n+@test \"standard: no bucket specified\" {\n+  run mkwheelhouse\n+  [[ \"$status\" -eq 2 ]]\n+  [[ \"$output\" == *\"too few arguments\"* || $output == *\"the following arguments are required: bucket\"* ]]\n+}\n+\n+@test \"standard: no package or requirement specified\" {\n+  run mkwheelhouse \"$MKWHEELHOUSE_BUCKET_STANDARD\"\n+  [[ \"$status\" -eq 2 ]]\n+  [[ \"$output\" == *\"specify at least one requirements file or package\"* ]]\n+}\n+\n+@test \"standard: pip can't install excluded packages\" {\n+  run pip install \\\n+    --no-index \\\n+    --find-links \"http://s3.amazonaws.com/$MKWHEELHOUSE_BUCKET_STANDARD/index.html\" \\\n+    unittest2\n+  [[ \"$status\" -eq 1 ]]\n+  [[ \"$output\" == *\"No distributions at all found for unittest2\"* ]]\n+}\n+\n+@test \"standard: pip can install built packages\" {\n+  pip install \\\n+    --no-index \\\n+    --find-links \"http://s3.amazonaws.com/$MKWHEELHOUSE_BUCKET_STANDARD/index.html\" \\\n+    six pytsdb\n+}\n+\n+@test \"nonstandard: packages only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" six\n+}\n+\n+@test \"nonstandard: -r only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" \\\n+    -r \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"nonstandard: --requirement only\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"nonstandard: --requirement and package\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/default.txt\"\n+}\n+\n+@test \"nonstandard: -e\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/exclusions.txt\" \\\n+    -e unittest2-1.0.1-py2.py3-none-any.whl\n+}\n+\n+@test \"nonstandard: --exclude\" {\n+  mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\" \\\n+    --requirement \"$BATS_TEST_DIRNAME/requirements/exclusions.txt\" \\\n+    --exclude unittest2-1.0.1-py2.py3-none-any.whl\n+}\n+\n+@test \"nonstandard: no bucket specified\" {\n+  run mkwheelhouse\n+  [[ \"$status\" -eq 2 ]]\n+  [[ \"$output\" == *\"too few arguments\"* || $output == *\"the following arguments are required: bucket\"* ]]\n+}\n+\n+@test \"nonstandard: no package or requirement specified\" {\n+  run mkwheelhouse \"$MKWHEELHOUSE_BUCKET_NONSTANDARD\"\n+  [[ \"$status\" -eq 2 ]]\n+  [[ \"$output\" == *\"specify at least one requirements file or package\"* ]]\n+}\n+\n+@test \"nonstandard: pip can't install excluded packages\" {\n+  run pip install \\\n+    --no-index \\\n+    --find-links \"http://s3.amazonaws.com/$MKWHEELHOUSE_BUCKET_NONSTANDARD/index.html\" \\\n+    unittest2\n+  [[ \"$status\" -eq 1 ]]\n+  [[ \"$output\" == *\"No distributions at all found for unittest2\"* ]]\n+}\n+\n+@test \"nonstandard: pip can install built packages\" {\n+  pip install \\\n+    --no-index \\\n+    --find-links \"http://s3.amazonaws.com/$MKWHEELHOUSE_BUCKET_NONSTANDARD/index.html\" \\\n+    six pytsdb\n+}\n", "problem_statement": "", "hints_text": "", "created_at": "2015-04-24T01:15:01Z"}