We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Rename Buildkite assets for clarity
## Summary

When downloading builds from `buildkite/kolibri/assets` details link, filenames are too complex and difficult to distinguish. 

![selection_655](https://user-images.githubusercontent.com/1457929/31338580-259d1370-ad00-11e7-9c8a-f890d2515631.png)

These links do save some time, but filenames are longer then those downloaded individually from Buildkite (green). Could we make them shorter? For example, get rid of the useless prefix and various `%2F` in between in order to make this:

`kolibri%2Fbuildkite%2Fbuild-2313%2F2755%2Fkolibri-0.6.dev020170929214748-git.pex` (red)

into this:

`build-2313-kolibri-0.6.dev020170929214748-git.pex` (yellow)

Or just `kolibri-0.6.dev020170929214748-git.pex` if those build details are not necessary.

![selection_653](https://user-images.githubusercontent.com/1457929/31339729-198fddf2-ad04-11e7-8b85-d1e0125600e4.png)

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `.buildkite/upload_artifacts.py`
Content:
```
1 """
2 # Requirements:
3     * Generate access token in your Github account, then create environment variable GITHUB_ACCESS_TOKEN.
4         - e.g export GITHUB_ACCESS_TOKEN=1ns3rt-my-t0k3n-h3re.
5 
6     * Generate a service account key for your Google API credentials, then create environment variable GOOGLE_APPLICATION_CREDENTIALS.
7         - e.g export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json.
8 
9 # Environment Variable/s:
10     * IS_KOLIBRI_RELEASE = Upload artifacts to the Google Cloud as a release candidate.
11     * GITHUB_ACCESS_TOKEN = Personal access token used to authenticate in your Github account via API.
12     * BUILDKITE_BUILD_NUMBER = Build identifier for each directory created.
13     * BUILDKITE_PULL_REQUEST = Pull request issue or the value is false.
14     * BUILDKITE_TAG = Tag identifier if this build was built from a tag.
15     * BUILDKITE_COMMIT = Git commit hash that the build was made from.
16     * GOOGLE_APPLICATION_CREDENTIALS = Your service account key.
17 """
18 import logging
19 import os
20 import sys
21 from os import listdir
22 
23 import requests
24 from gcloud import storage
25 from github3 import login
26 
27 logging.getLogger().setLevel(logging.INFO)
28 
29 ACCESS_TOKEN = os.getenv("GITHUB_ACCESS_TOKEN")
30 REPO_OWNER = "learningequality"
31 REPO_NAME = "kolibri"
32 ISSUE_ID = os.getenv("BUILDKITE_PULL_REQUEST")
33 BUILD_ID = os.getenv("BUILDKITE_BUILD_NUMBER")
34 TAG = os.getenv("BUILDKITE_TAG")
35 COMMIT = os.getenv("BUILDKITE_COMMIT")
36 
37 
38 RELEASE_DIR = 'release'
39 PROJECT_PATH = os.path.join(os.getcwd())
40 
41 # Python packages artifact location
42 DIST_DIR = os.path.join(PROJECT_PATH, "dist")
43 
44 # Installer artifact location
45 INSTALLER_DIR = os.path.join(PROJECT_PATH, "installer")
46 
47 headers = {'Authorization': 'token %s' % ACCESS_TOKEN}
48 
49 INSTALLER_CAT = 'Installers'
50 
51 PYTHON_PKG_CAT = 'Python packages'
52 
53 # Manifest of files, keyed by extension
54 file_manifest = {
55     'exe': {
56         'extension': 'exe',
57         'description': 'Windows Installer',
58         'category': INSTALLER_CAT,
59         'content_type': 'application/x-ms-dos-executable',
60     },
61     'pex': {
62         'extension': 'pex',
63         'description': 'Pex file',
64         'category': PYTHON_PKG_CAT,
65         'content_type': 'application/octet-stream',
66     },
67     'whl': {
68         'extension': 'whl',
69         'description': 'Whl file',
70         'category': PYTHON_PKG_CAT,
71         'content_type': 'application/zip',
72     },
73     'gz': {
74         'extension': 'gz',
75         'description': 'Tar file',
76         'category': PYTHON_PKG_CAT,
77         'content_type': 'application/gzip',
78     },
79     'apk': {
80         'extension': 'apk',
81         'description': 'Android Installer',
82         'category': INSTALLER_CAT,
83         'content_type': 'application/vnd.android.package-archive',
84     },
85 }
86 
87 file_order = [
88     'exe',
89     'apk',
90     'pex',
91     'whl',
92     'gz',
93 ]
94 
95 gh = login(token=ACCESS_TOKEN)
96 repository = gh.repository(REPO_OWNER, REPO_NAME)
97 
98 
99 def create_status_report_html(artifacts):
100     """
101     Create html page to list build artifacts for linking from github status.
102     """
103     html = "<html>\n<body>\n<h1>Build Artifacts</h1>\n"
104     current_heading = None
105     for ext in file_order:
106         artifact = artifacts[ext]
107         if artifact['category'] != current_heading:
108             current_heading = artifact['category']
109             html += "<h2>{heading}</h2>\n".format(heading=current_heading)
110         html += "<p>{description}: <a href='{media_url}'>{name}</a></p>\n".format(
111             **artifact
112         )
113     html += "</body>\n</html>"
114     return html
115 
116 def create_github_status(report_url):
117     """
118     Create a github status with a link to the report URL,
119     only do this once buildkite has been successful, so only report success here.
120     """
121     status = repository.create_status(
122         COMMIT,
123         "success",
124         target_url=report_url,
125         description="Kolibri Buildkite assets",
126         context="buildkite/kolibri/assets"
127     )
128     if status:
129         logging.info('Successfully created Github status for commit %s.' % COMMIT)
130     else:
131         logging.info('Error encounter. Now exiting!')
132         sys.exit(1)
133 
134 
135 def collect_local_artifacts():
136     """
137     Create a dict of the artifact name and the location.
138     """
139 
140     artifacts_dict = {}
141 
142     def create_artifact_data(artifact_dir):
143         for artifact in listdir(artifact_dir):
144             filename, file_extension = os.path.splitext(artifact)
145             # Remove leading '.'
146             file_extension = file_extension[1:]
147             if file_extension in file_manifest:
148                 data = {"name": artifact,
149                         "file_location": "%s/%s" % (artifact_dir, artifact)}
150                 data.update(file_manifest[file_extension])
151                 logging.info("Collect file data: (%s)" % data)
152                 artifacts_dict[file_extension] = data
153     create_artifact_data(DIST_DIR)
154     create_artifact_data(INSTALLER_DIR)
155     return artifacts_dict
156 
157 
158 def upload_artifacts():
159     """
160     Upload the artifacts on the Google Cloud Storage.
161     Create a comment on the pull requester with artifact media link.
162     """
163     client = storage.Client()
164     bucket = client.bucket("le-downloads")
165     artifacts = collect_local_artifacts()
166     is_release = os.getenv("IS_KOLIBRI_RELEASE")
167     for file_data in artifacts.values():
168         logging.info("Uploading file (%s)" % (file_data.get("name")))
169         if is_release:
170             blob = bucket.blob('kolibri/%s/%s/%s' % (RELEASE_DIR, BUILD_ID, file_data.get("name")))
171         else:
172             blob = bucket.blob('kolibri/buildkite/build-%s/%s/%s' % (ISSUE_ID, BUILD_ID, file_data.get("name")))
173         blob.upload_from_filename(filename=file_data.get("file_location"))
174         blob.make_public()
175         file_data.update({'media_url': blob.media_link})
176 
177     html = create_status_report_html(artifacts)
178 
179     blob = bucket.blob('kolibri/%s/%s/report.html' % (RELEASE_DIR, BUILD_ID))
180 
181     blob.upload_from_string(html, content_type='text/html')
182 
183     blob.make_public()
184 
185     create_github_status(blob.public_url)
186 
187     if TAG:
188         # Building from a tag, this is probably a release!
189         # Have to do this with requests because github3 does not support this interface yet
190         get_release_asset_url = requests.get("https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}".format(
191             owner=REPO_OWNER,
192             repo=REPO_NAME,
193             tag=TAG,
194         ))
195         if get_release_asset_url.status_code == 200:
196             # Definitely a release!
197             release_id = get_release_asset_url.json()['id']
198             release_name = get_release_asset_url.json()['name']
199             release = repository.release(id=release_id)
200             logging.info("Uploading built assets to Github Release: %s" % release_name)
201             for file_extension in file_order:
202                 artifact = artifacts[file_extension]
203                 logging.info("Uploading release asset: %s" % (artifact.get("name")))
204                 # For some reason github3 does not let us set a label at initial upload
205                 asset = release.upload_asset(
206                     content_type=artifact['content_type'],
207                     name=artifact['name'],
208                     asset=open(artifact['file_location'], 'rb')
209                 )
210                 if asset:
211                     # So do it after the initial upload instead
212                     asset.edit(artifact['name'], label=artifact['description'])
213                     logging.info("Successfully uploaded release asset: %s" % (artifact.get('name')))
214                 else:
215                     logging.error("Error uploading release asset: %s" % (artifact.get('name')))
216 
217 
218 def main():
219     upload_artifacts()
220 
221 
222 if __name__ == "__main__":
223     main()
224
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/.buildkite/upload_artifacts.py b/.buildkite/upload_artifacts.py
--- a/.buildkite/upload_artifacts.py
+++ b/.buildkite/upload_artifacts.py
@@ -167,16 +167,16 @@
     for file_data in artifacts.values():
         logging.info("Uploading file (%s)" % (file_data.get("name")))
         if is_release:
-            blob = bucket.blob('kolibri/%s/%s/%s' % (RELEASE_DIR, BUILD_ID, file_data.get("name")))
+            blob = bucket.blob('kolibri-%s-%s-%s' % (RELEASE_DIR, BUILD_ID, file_data.get("name")))
         else:
-            blob = bucket.blob('kolibri/buildkite/build-%s/%s/%s' % (ISSUE_ID, BUILD_ID, file_data.get("name")))
+            blob = bucket.blob('kolibri-buildkite-build-%s-%s-%s' % (ISSUE_ID, BUILD_ID, file_data.get("name")))
         blob.upload_from_filename(filename=file_data.get("file_location"))
         blob.make_public()
         file_data.update({'media_url': blob.media_link})
 
     html = create_status_report_html(artifacts)
 
-    blob = bucket.blob('kolibri/%s/%s/report.html' % (RELEASE_DIR, BUILD_ID))
+    blob = bucket.blob('kolibri-%s-%s-report.html' % (RELEASE_DIR, BUILD_ID))
 
     blob.upload_from_string(html, content_type='text/html')

{"golden_diff": "diff --git a/.buildkite/upload_artifacts.py b/.buildkite/upload_artifacts.py\n--- a/.buildkite/upload_artifacts.py\n+++ b/.buildkite/upload_artifacts.py\n@@ -167,16 +167,16 @@\n     for file_data in artifacts.values():\n         logging.info(\"Uploading file (%s)\" % (file_data.get(\"name\")))\n         if is_release:\n-            blob = bucket.blob('kolibri/%s/%s/%s' % (RELEASE_DIR, BUILD_ID, file_data.get(\"name\")))\n+            blob = bucket.blob('kolibri-%s-%s-%s' % (RELEASE_DIR, BUILD_ID, file_data.get(\"name\")))\n         else:\n-            blob = bucket.blob('kolibri/buildkite/build-%s/%s/%s' % (ISSUE_ID, BUILD_ID, file_data.get(\"name\")))\n+            blob = bucket.blob('kolibri-buildkite-build-%s-%s-%s' % (ISSUE_ID, BUILD_ID, file_data.get(\"name\")))\n         blob.upload_from_filename(filename=file_data.get(\"file_location\"))\n         blob.make_public()\n         file_data.update({'media_url': blob.media_link})\n \n     html = create_status_report_html(artifacts)\n \n-    blob = bucket.blob('kolibri/%s/%s/report.html' % (RELEASE_DIR, BUILD_ID))\n+    blob = bucket.blob('kolibri-%s-%s-report.html' % (RELEASE_DIR, BUILD_ID))\n \n     blob.upload_from_string(html, content_type='text/html')\n", "issue": "Rename Buildkite assets for clarity\n## Summary\r\n\r\nWhen downloading builds from `buildkite/kolibri/assets` details link, filenames are too complex and difficult to distinguish. \r\n\r\n![selection_655](https://user-images.githubusercontent.com/1457929/31338580-259d1370-ad00-11e7-9c8a-f890d2515631.png)\r\n\r\nThese links do save some time, but filenames are longer then those downloaded individually from Buildkite (green). Could we make them shorter? For example, get rid of the useless prefix and various `%2F` in between in order to make this:\r\n\r\n`kolibri%2Fbuildkite%2Fbuild-2313%2F2755%2Fkolibri-0.6.dev020170929214748-git.pex` (red)\r\n\r\ninto this:\r\n\r\n`build-2313-kolibri-0.6.dev020170929214748-git.pex` (yellow)\r\n\r\nOr just `kolibri-0.6.dev020170929214748-git.pex` if those build details are not necessary.\r\n\r\n![selection_653](https://user-images.githubusercontent.com/1457929/31339729-198fddf2-ad04-11e7-8b85-d1e0125600e4.png)\n", "before_files": [{"content": "\"\"\"\n# Requirements:\n    * Generate access token in your Github account, then create environment variable GITHUB_ACCESS_TOKEN.\n        - e.g export GITHUB_ACCESS_TOKEN=1ns3rt-my-t0k3n-h3re.\n\n    * Generate a service account key for your Google API credentials, then create environment variable GOOGLE_APPLICATION_CREDENTIALS.\n        - e.g export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json.\n\n# Environment Variable/s:\n    * IS_KOLIBRI_RELEASE = Upload artifacts to the Google Cloud as a release candidate.\n    * GITHUB_ACCESS_TOKEN = Personal access token used to authenticate in your Github account via API.\n    * BUILDKITE_BUILD_NUMBER = Build identifier for each directory created.\n    * BUILDKITE_PULL_REQUEST = Pull request issue or the value is false.\n    * BUILDKITE_TAG = Tag identifier if this build was built from a tag.\n    * BUILDKITE_COMMIT = Git commit hash that the build was made from.\n    * GOOGLE_APPLICATION_CREDENTIALS = Your service account key.\n\"\"\"\nimport logging\nimport os\nimport sys\nfrom os import listdir\n\nimport requests\nfrom gcloud import storage\nfrom github3 import login\n\nlogging.getLogger().setLevel(logging.INFO)\n\nACCESS_TOKEN = os.getenv(\"GITHUB_ACCESS_TOKEN\")\nREPO_OWNER = \"learningequality\"\nREPO_NAME = \"kolibri\"\nISSUE_ID = os.getenv(\"BUILDKITE_PULL_REQUEST\")\nBUILD_ID = os.getenv(\"BUILDKITE_BUILD_NUMBER\")\nTAG = os.getenv(\"BUILDKITE_TAG\")\nCOMMIT = os.getenv(\"BUILDKITE_COMMIT\")\n\n\nRELEASE_DIR = 'release'\nPROJECT_PATH = os.path.join(os.getcwd())\n\n# Python packages artifact location\nDIST_DIR = os.path.join(PROJECT_PATH, \"dist\")\n\n# Installer artifact location\nINSTALLER_DIR = os.path.join(PROJECT_PATH, \"installer\")\n\nheaders = {'Authorization': 'token %s' % ACCESS_TOKEN}\n\nINSTALLER_CAT = 'Installers'\n\nPYTHON_PKG_CAT = 'Python packages'\n\n# Manifest of files, keyed by extension\nfile_manifest = {\n    'exe': {\n        'extension': 'exe',\n        'description': 'Windows Installer',\n        'category': INSTALLER_CAT,\n        'content_type': 'application/x-ms-dos-executable',\n    },\n    'pex': {\n        'extension': 'pex',\n        'description': 'Pex file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/octet-stream',\n    },\n    'whl': {\n        'extension': 'whl',\n        'description': 'Whl file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/zip',\n    },\n    'gz': {\n        'extension': 'gz',\n        'description': 'Tar file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/gzip',\n    },\n    'apk': {\n        'extension': 'apk',\n        'description': 'Android Installer',\n        'category': INSTALLER_CAT,\n        'content_type': 'application/vnd.android.package-archive',\n    },\n}\n\nfile_order = [\n    'exe',\n    'apk',\n    'pex',\n    'whl',\n    'gz',\n]\n\ngh = login(token=ACCESS_TOKEN)\nrepository = gh.repository(REPO_OWNER, REPO_NAME)\n\n\ndef create_status_report_html(artifacts):\n    \"\"\"\n    Create html page to list build artifacts for linking from github status.\n    \"\"\"\n    html = \"<html>\\n<body>\\n<h1>Build Artifacts</h1>\\n\"\n    current_heading = None\n    for ext in file_order:\n        artifact = artifacts[ext]\n        if artifact['category'] != current_heading:\n            current_heading = artifact['category']\n            html += \"<h2>{heading}</h2>\\n\".format(heading=current_heading)\n        html += \"<p>{description}: <a href='{media_url}'>{name}</a></p>\\n\".format(\n            **artifact\n        )\n    html += \"</body>\\n</html>\"\n    return html\n\ndef create_github_status(report_url):\n    \"\"\"\n    Create a github status with a link to the report URL,\n    only do this once buildkite has been successful, so only report success here.\n    \"\"\"\n    status = repository.create_status(\n        COMMIT,\n        \"success\",\n        target_url=report_url,\n        description=\"Kolibri Buildkite assets\",\n        context=\"buildkite/kolibri/assets\"\n    )\n    if status:\n        logging.info('Successfully created Github status for commit %s.' % COMMIT)\n    else:\n        logging.info('Error encounter. Now exiting!')\n        sys.exit(1)\n\n\ndef collect_local_artifacts():\n    \"\"\"\n    Create a dict of the artifact name and the location.\n    \"\"\"\n\n    artifacts_dict = {}\n\n    def create_artifact_data(artifact_dir):\n        for artifact in listdir(artifact_dir):\n            filename, file_extension = os.path.splitext(artifact)\n            # Remove leading '.'\n            file_extension = file_extension[1:]\n            if file_extension in file_manifest:\n                data = {\"name\": artifact,\n                        \"file_location\": \"%s/%s\" % (artifact_dir, artifact)}\n                data.update(file_manifest[file_extension])\n                logging.info(\"Collect file data: (%s)\" % data)\n                artifacts_dict[file_extension] = data\n    create_artifact_data(DIST_DIR)\n    create_artifact_data(INSTALLER_DIR)\n    return artifacts_dict\n\n\ndef upload_artifacts():\n    \"\"\"\n    Upload the artifacts on the Google Cloud Storage.\n    Create a comment on the pull requester with artifact media link.\n    \"\"\"\n    client = storage.Client()\n    bucket = client.bucket(\"le-downloads\")\n    artifacts = collect_local_artifacts()\n    is_release = os.getenv(\"IS_KOLIBRI_RELEASE\")\n    for file_data in artifacts.values():\n        logging.info(\"Uploading file (%s)\" % (file_data.get(\"name\")))\n        if is_release:\n            blob = bucket.blob('kolibri/%s/%s/%s' % (RELEASE_DIR, BUILD_ID, file_data.get(\"name\")))\n        else:\n            blob = bucket.blob('kolibri/buildkite/build-%s/%s/%s' % (ISSUE_ID, BUILD_ID, file_data.get(\"name\")))\n        blob.upload_from_filename(filename=file_data.get(\"file_location\"))\n        blob.make_public()\n        file_data.update({'media_url': blob.media_link})\n\n    html = create_status_report_html(artifacts)\n\n    blob = bucket.blob('kolibri/%s/%s/report.html' % (RELEASE_DIR, BUILD_ID))\n\n    blob.upload_from_string(html, content_type='text/html')\n\n    blob.make_public()\n\n    create_github_status(blob.public_url)\n\n    if TAG:\n        # Building from a tag, this is probably a release!\n        # Have to do this with requests because github3 does not support this interface yet\n        get_release_asset_url = requests.get(\"https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}\".format(\n            owner=REPO_OWNER,\n            repo=REPO_NAME,\n            tag=TAG,\n        ))\n        if get_release_asset_url.status_code == 200:\n            # Definitely a release!\n            release_id = get_release_asset_url.json()['id']\n            release_name = get_release_asset_url.json()['name']\n            release = repository.release(id=release_id)\n            logging.info(\"Uploading built assets to Github Release: %s\" % release_name)\n            for file_extension in file_order:\n                artifact = artifacts[file_extension]\n                logging.info(\"Uploading release asset: %s\" % (artifact.get(\"name\")))\n                # For some reason github3 does not let us set a label at initial upload\n                asset = release.upload_asset(\n                    content_type=artifact['content_type'],\n                    name=artifact['name'],\n                    asset=open(artifact['file_location'], 'rb')\n                )\n                if asset:\n                    # So do it after the initial upload instead\n                    asset.edit(artifact['name'], label=artifact['description'])\n                    logging.info(\"Successfully uploaded release asset: %s\" % (artifact.get('name')))\n                else:\n                    logging.error(\"Error uploading release asset: %s\" % (artifact.get('name')))\n\n\ndef main():\n    upload_artifacts()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": ".buildkite/upload_artifacts.py"}], "after_files": [{"content": "\"\"\"\n# Requirements:\n    * Generate access token in your Github account, then create environment variable GITHUB_ACCESS_TOKEN.\n        - e.g export GITHUB_ACCESS_TOKEN=1ns3rt-my-t0k3n-h3re.\n\n    * Generate a service account key for your Google API credentials, then create environment variable GOOGLE_APPLICATION_CREDENTIALS.\n        - e.g export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json.\n\n# Environment Variable/s:\n    * IS_KOLIBRI_RELEASE = Upload artifacts to the Google Cloud as a release candidate.\n    * GITHUB_ACCESS_TOKEN = Personal access token used to authenticate in your Github account via API.\n    * BUILDKITE_BUILD_NUMBER = Build identifier for each directory created.\n    * BUILDKITE_PULL_REQUEST = Pull request issue or the value is false.\n    * BUILDKITE_TAG = Tag identifier if this build was built from a tag.\n    * BUILDKITE_COMMIT = Git commit hash that the build was made from.\n    * GOOGLE_APPLICATION_CREDENTIALS = Your service account key.\n\"\"\"\nimport logging\nimport os\nimport sys\nfrom os import listdir\n\nimport requests\nfrom gcloud import storage\nfrom github3 import login\n\nlogging.getLogger().setLevel(logging.INFO)\n\nACCESS_TOKEN = os.getenv(\"GITHUB_ACCESS_TOKEN\")\nREPO_OWNER = \"learningequality\"\nREPO_NAME = \"kolibri\"\nISSUE_ID = os.getenv(\"BUILDKITE_PULL_REQUEST\")\nBUILD_ID = os.getenv(\"BUILDKITE_BUILD_NUMBER\")\nTAG = os.getenv(\"BUILDKITE_TAG\")\nCOMMIT = os.getenv(\"BUILDKITE_COMMIT\")\n\n\nRELEASE_DIR = 'release'\nPROJECT_PATH = os.path.join(os.getcwd())\n\n# Python packages artifact location\nDIST_DIR = os.path.join(PROJECT_PATH, \"dist\")\n\n# Installer artifact location\nINSTALLER_DIR = os.path.join(PROJECT_PATH, \"installer\")\n\nheaders = {'Authorization': 'token %s' % ACCESS_TOKEN}\n\nINSTALLER_CAT = 'Installers'\n\nPYTHON_PKG_CAT = 'Python packages'\n\n# Manifest of files, keyed by extension\nfile_manifest = {\n    'exe': {\n        'extension': 'exe',\n        'description': 'Windows Installer',\n        'category': INSTALLER_CAT,\n        'content_type': 'application/x-ms-dos-executable',\n    },\n    'pex': {\n        'extension': 'pex',\n        'description': 'Pex file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/octet-stream',\n    },\n    'whl': {\n        'extension': 'whl',\n        'description': 'Whl file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/zip',\n    },\n    'gz': {\n        'extension': 'gz',\n        'description': 'Tar file',\n        'category': PYTHON_PKG_CAT,\n        'content_type': 'application/gzip',\n    },\n    'apk': {\n        'extension': 'apk',\n        'description': 'Android Installer',\n        'category': INSTALLER_CAT,\n        'content_type': 'application/vnd.android.package-archive',\n    },\n}\n\nfile_order = [\n    'exe',\n    'apk',\n    'pex',\n    'whl',\n    'gz',\n]\n\ngh = login(token=ACCESS_TOKEN)\nrepository = gh.repository(REPO_OWNER, REPO_NAME)\n\n\ndef create_status_report_html(artifacts):\n    \"\"\"\n    Create html page to list build artifacts for linking from github status.\n    \"\"\"\n    html = \"<html>\\n<body>\\n<h1>Build Artifacts</h1>\\n\"\n    current_heading = None\n    for ext in file_order:\n        artifact = artifacts[ext]\n        if artifact['category'] != current_heading:\n            current_heading = artifact['category']\n            html += \"<h2>{heading}</h2>\\n\".format(heading=current_heading)\n        html += \"<p>{description}: <a href='{media_url}'>{name}</a></p>\\n\".format(\n            **artifact\n        )\n    html += \"</body>\\n</html>\"\n    return html\n\ndef create_github_status(report_url):\n    \"\"\"\n    Create a github status with a link to the report URL,\n    only do this once buildkite has been successful, so only report success here.\n    \"\"\"\n    status = repository.create_status(\n        COMMIT,\n        \"success\",\n        target_url=report_url,\n        description=\"Kolibri Buildkite assets\",\n        context=\"buildkite/kolibri/assets\"\n    )\n    if status:\n        logging.info('Successfully created Github status for commit %s.' % COMMIT)\n    else:\n        logging.info('Error encounter. Now exiting!')\n        sys.exit(1)\n\n\ndef collect_local_artifacts():\n    \"\"\"\n    Create a dict of the artifact name and the location.\n    \"\"\"\n\n    artifacts_dict = {}\n\n    def create_artifact_data(artifact_dir):\n        for artifact in listdir(artifact_dir):\n            filename, file_extension = os.path.splitext(artifact)\n            # Remove leading '.'\n            file_extension = file_extension[1:]\n            if file_extension in file_manifest:\n                data = {\"name\": artifact,\n                        \"file_location\": \"%s/%s\" % (artifact_dir, artifact)}\n                data.update(file_manifest[file_extension])\n                logging.info(\"Collect file data: (%s)\" % data)\n                artifacts_dict[file_extension] = data\n    create_artifact_data(DIST_DIR)\n    create_artifact_data(INSTALLER_DIR)\n    return artifacts_dict\n\n\ndef upload_artifacts():\n    \"\"\"\n    Upload the artifacts on the Google Cloud Storage.\n    Create a comment on the pull requester with artifact media link.\n    \"\"\"\n    client = storage.Client()\n    bucket = client.bucket(\"le-downloads\")\n    artifacts = collect_local_artifacts()\n    is_release = os.getenv(\"IS_KOLIBRI_RELEASE\")\n    for file_data in artifacts.values():\n        logging.info(\"Uploading file (%s)\" % (file_data.get(\"name\")))\n        if is_release:\n            blob = bucket.blob('kolibri-%s-%s-%s' % (RELEASE_DIR, BUILD_ID, file_data.get(\"name\")))\n        else:\n            blob = bucket.blob('kolibri-buildkite-build-%s-%s-%s' % (ISSUE_ID, BUILD_ID, file_data.get(\"name\")))\n        blob.upload_from_filename(filename=file_data.get(\"file_location\"))\n        blob.make_public()\n        file_data.update({'media_url': blob.media_link})\n\n    html = create_status_report_html(artifacts)\n\n    blob = bucket.blob('kolibri-%s-%s-report.html' % (RELEASE_DIR, BUILD_ID))\n\n    blob.upload_from_string(html, content_type='text/html')\n\n    blob.make_public()\n\n    create_github_status(blob.public_url)\n\n    if TAG:\n        # Building from a tag, this is probably a release!\n        # Have to do this with requests because github3 does not support this interface yet\n        get_release_asset_url = requests.get(\"https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}\".format(\n            owner=REPO_OWNER,\n            repo=REPO_NAME,\n            tag=TAG,\n        ))\n        if get_release_asset_url.status_code == 200:\n            # Definitely a release!\n            release_id = get_release_asset_url.json()['id']\n            release_name = get_release_asset_url.json()['name']\n            release = repository.release(id=release_id)\n            logging.info(\"Uploading built assets to Github Release: %s\" % release_name)\n            for file_extension in file_order:\n                artifact = artifacts[file_extension]\n                logging.info(\"Uploading release asset: %s\" % (artifact.get(\"name\")))\n                # For some reason github3 does not let us set a label at initial upload\n                asset = release.upload_asset(\n                    content_type=artifact['content_type'],\n                    name=artifact['name'],\n                    asset=open(artifact['file_location'], 'rb')\n                )\n                if asset:\n                    # So do it after the initial upload instead\n                    asset.edit(artifact['name'], label=artifact['description'])\n                    logging.info(\"Successfully uploaded release asset: %s\" % (artifact.get('name')))\n                else:\n                    logging.error(\"Error uploading release asset: %s\" % (artifact.get('name')))\n\n\ndef main():\n    upload_artifacts()\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": ".buildkite/upload_artifacts.py"}]}