We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error building when previous build was stoped.
Trying to build a package whose previous build was canceled halfway. 

The solution is to remove the previous tar (corrupted) that is obtained with `conda build --output .`
There should be a nice error message, requesting the deletion .

```
 File "/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/build.py", line 339, in build
    override_channels=override_channels)
  File "/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/build.py", line 244, in create_env
    update_index(config.bldpkgs_dir)
  File "/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/index.py", line 87, in update_index
    d = read_index_tar(path)
  File "/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/index.py", line 21, in read_index_tar
    with tarfile.open(tar_path) as t:
  File "/Users/pedro/anaconda/lib/python2.7/tarfile.py", line 1672, in open
    raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully
```

```
Current conda install:

             platform : osx-64
        conda version : 3.14.0


conda-build version : 1.14.0
       python version : 2.7.10.final.0
     requests version : 2.7.0
     root environment : /Users/pedro/anaconda  (writable)
  default environment : /Users/pedro/anaconda
     envs directories : /Users/pedro/anaconda/envs
        package cache : /Users/pedro/anaconda/pkgs
         channel URLs : https://repo.continuum.io/pkgs/free/osx-64/
                        https://repo.continuum.io/pkgs/free/noarch/
                        https://repo.continuum.io/pkgs/pro/osx-64/
                        https://repo.continuum.io/pkgs/pro/noarch/
          config file : None
    is foreign system : False
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `conda_build/index.py`
Content:
```
1 '''
2 Functions related to creating repodata index files.
3 '''
4 
5 from __future__ import absolute_import, division, print_function
6 
7 import os
8 import bz2
9 import sys
10 import json
11 import tarfile
12 from os.path import isfile, join, getmtime
13 
14 from conda_build.utils import file_info
15 from conda.compat import PY3
16 from conda.utils import md5_file
17 
18 
19 def read_index_tar(tar_path):
20     """ Returns the index.json dict inside the given package tarball. """
21     with tarfile.open(tar_path) as t:
22         try:
23             return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))
24         except EOFError:
25             raise RuntimeError("Could not extract %s. File probably corrupt."
26                 % tar_path)
27         except OSError as e:
28             raise RuntimeError("Could not extract %s (%s)" % (tar_path, e))
29 
30 def write_repodata(repodata, dir_path):
31     """ Write updated repodata.json and repodata.json.bz2 """
32     data = json.dumps(repodata, indent=2, sort_keys=True)
33     # strip trailing whitespace
34     data = '\n'.join(line.rstrip() for line in data.split('\n'))
35     # make sure we have newline at the end
36     if not data.endswith('\n'):
37         data += '\n'
38     with open(join(dir_path, 'repodata.json'), 'w') as fo:
39         fo.write(data)
40     with open(join(dir_path, 'repodata.json.bz2'), 'wb') as fo:
41         fo.write(bz2.compress(data.encode('utf-8')))
42 
43 def update_index(dir_path, verbose=False, force=False, check_md5=False, remove=True):
44     """
45     Update all index files in dir_path with changed packages.
46 
47     :param verbose: Should detailed status messages be output?
48     :type verbose: bool
49     :param force: Whether to re-index all packages (including those that
50                   haven't changed) or not.
51     :type force: bool
52     :param check_md5: Whether to check MD5s instead of mtimes for determining
53                       if a package changed.
54     :type check_md5: bool
55     """
56     if verbose:
57         print("updating index in:", dir_path)
58     index_path = join(dir_path, '.index.json')
59     if force:
60         index = {}
61     else:
62         try:
63             mode_dict = {'mode': 'r', 'encoding': 'utf-8'} if PY3 else {'mode': 'rb'}
64             with open(index_path, **mode_dict) as fi:
65                 index = json.load(fi)
66         except (IOError, ValueError):
67             index = {}
68 
69     files = set(fn for fn in os.listdir(dir_path) if fn.endswith('.tar.bz2'))
70     if any(fn.startswith('_license-') for fn in files):
71         sys.exit("""\
72 Error:
73     Indexing a copy of the Anaconda conda package channel is neither
74     necessary nor supported.  If you which to add your own packages,
75     you can do so by adding them to a separate channel.
76 """)
77     for fn in files:
78         path = join(dir_path, fn)
79         if fn in index:
80             if check_md5:
81                 if index[fn]['md5'] == md5_file(path):
82                     continue
83             elif index[fn]['mtime'] == getmtime(path):
84                 continue
85         if verbose:
86             print('updating:', fn)
87         d = read_index_tar(path)
88         d.update(file_info(path))
89         index[fn] = d
90 
91     for fn in files:
92         index[fn]['sig'] = '.' if isfile(join(dir_path, fn + '.sig')) else None
93 
94     if remove:
95         # remove files from the index which are not on disk
96         for fn in set(index) - files:
97             if verbose:
98                 print("removing:", fn)
99             del index[fn]
100 
101     # Deal with Python 2 and 3's different json module type reqs
102     mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}
103     with open(index_path, **mode_dict) as fo:
104         json.dump(index, fo, indent=2, sort_keys=True, default=str)
105 
106     # --- new repodata
107     for fn in index:
108         info = index[fn]
109         for varname in 'arch', 'platform', 'mtime', 'ucs':
110             try:
111                 del info[varname]
112             except KeyError:
113                 pass
114 
115         if 'requires' in info and 'depends' not in info:
116             info['depends'] = info['requires']
117 
118     repodata = {'packages': index, 'info': {}}
119     write_repodata(repodata, dir_path)
120
```
--- 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/conda_build/index.py b/conda_build/index.py
--- a/conda_build/index.py
+++ b/conda_build/index.py
@@ -18,14 +18,17 @@
 
 def read_index_tar(tar_path):
     """ Returns the index.json dict inside the given package tarball. """
-    with tarfile.open(tar_path) as t:
-        try:
-            return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))
-        except EOFError:
-            raise RuntimeError("Could not extract %s. File probably corrupt."
-                % tar_path)
-        except OSError as e:
-            raise RuntimeError("Could not extract %s (%s)" % (tar_path, e))
+    try:
+        with tarfile.open(tar_path) as t:
+            try:
+                return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))
+            except EOFError:
+                raise RuntimeError("Could not extract %s. File probably corrupt."
+                    % tar_path)
+            except OSError as e:
+                raise RuntimeError("Could not extract %s (%s)" % (tar_path, e))
+    except tarfile.ReadError:
+        raise RuntimeError("Could not extract metadata from %s. File probably corrupt." % tar_path)
 
 def write_repodata(repodata, dir_path):
     """ Write updated repodata.json and repodata.json.bz2 """

{"golden_diff": "diff --git a/conda_build/index.py b/conda_build/index.py\n--- a/conda_build/index.py\n+++ b/conda_build/index.py\n@@ -18,14 +18,17 @@\n \n def read_index_tar(tar_path):\n     \"\"\" Returns the index.json dict inside the given package tarball. \"\"\"\n-    with tarfile.open(tar_path) as t:\n-        try:\n-            return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))\n-        except EOFError:\n-            raise RuntimeError(\"Could not extract %s. File probably corrupt.\"\n-                % tar_path)\n-        except OSError as e:\n-            raise RuntimeError(\"Could not extract %s (%s)\" % (tar_path, e))\n+    try:\n+        with tarfile.open(tar_path) as t:\n+            try:\n+                return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))\n+            except EOFError:\n+                raise RuntimeError(\"Could not extract %s. File probably corrupt.\"\n+                    % tar_path)\n+            except OSError as e:\n+                raise RuntimeError(\"Could not extract %s (%s)\" % (tar_path, e))\n+    except tarfile.ReadError:\n+        raise RuntimeError(\"Could not extract metadata from %s. File probably corrupt.\" % tar_path)\n \n def write_repodata(repodata, dir_path):\n     \"\"\" Write updated repodata.json and repodata.json.bz2 \"\"\"\n", "issue": "Error building when previous build was stoped.\nTrying to build a package whose previous build was canceled halfway. \n\nThe solution is to remove the previous tar (corrupted) that is obtained with `conda build --output .`\nThere should be a nice error message, requesting the deletion .\n\n```\n File \"/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/build.py\", line 339, in build\n    override_channels=override_channels)\n  File \"/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/build.py\", line 244, in create_env\n    update_index(config.bldpkgs_dir)\n  File \"/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/index.py\", line 87, in update_index\n    d = read_index_tar(path)\n  File \"/Users/pedro/anaconda/lib/python2.7/site-packages/conda_build/index.py\", line 21, in read_index_tar\n    with tarfile.open(tar_path) as t:\n  File \"/Users/pedro/anaconda/lib/python2.7/tarfile.py\", line 1672, in open\n    raise ReadError(\"file could not be opened successfully\")\ntarfile.ReadError: file could not be opened successfully\n```\n\n```\nCurrent conda install:\n\n             platform : osx-64\n        conda version : 3.14.0\n\n\nconda-build version : 1.14.0\n       python version : 2.7.10.final.0\n     requests version : 2.7.0\n     root environment : /Users/pedro/anaconda  (writable)\n  default environment : /Users/pedro/anaconda\n     envs directories : /Users/pedro/anaconda/envs\n        package cache : /Users/pedro/anaconda/pkgs\n         channel URLs : https://repo.continuum.io/pkgs/free/osx-64/\n                        https://repo.continuum.io/pkgs/free/noarch/\n                        https://repo.continuum.io/pkgs/pro/osx-64/\n                        https://repo.continuum.io/pkgs/pro/noarch/\n          config file : None\n    is foreign system : False\n```\n\n", "before_files": [{"content": "'''\nFunctions related to creating repodata index files.\n'''\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport bz2\nimport sys\nimport json\nimport tarfile\nfrom os.path import isfile, join, getmtime\n\nfrom conda_build.utils import file_info\nfrom conda.compat import PY3\nfrom conda.utils import md5_file\n\n\ndef read_index_tar(tar_path):\n    \"\"\" Returns the index.json dict inside the given package tarball. \"\"\"\n    with tarfile.open(tar_path) as t:\n        try:\n            return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))\n        except EOFError:\n            raise RuntimeError(\"Could not extract %s. File probably corrupt.\"\n                % tar_path)\n        except OSError as e:\n            raise RuntimeError(\"Could not extract %s (%s)\" % (tar_path, e))\n\ndef write_repodata(repodata, dir_path):\n    \"\"\" Write updated repodata.json and repodata.json.bz2 \"\"\"\n    data = json.dumps(repodata, indent=2, sort_keys=True)\n    # strip trailing whitespace\n    data = '\\n'.join(line.rstrip() for line in data.split('\\n'))\n    # make sure we have newline at the end\n    if not data.endswith('\\n'):\n        data += '\\n'\n    with open(join(dir_path, 'repodata.json'), 'w') as fo:\n        fo.write(data)\n    with open(join(dir_path, 'repodata.json.bz2'), 'wb') as fo:\n        fo.write(bz2.compress(data.encode('utf-8')))\n\ndef update_index(dir_path, verbose=False, force=False, check_md5=False, remove=True):\n    \"\"\"\n    Update all index files in dir_path with changed packages.\n\n    :param verbose: Should detailed status messages be output?\n    :type verbose: bool\n    :param force: Whether to re-index all packages (including those that\n                  haven't changed) or not.\n    :type force: bool\n    :param check_md5: Whether to check MD5s instead of mtimes for determining\n                      if a package changed.\n    :type check_md5: bool\n    \"\"\"\n    if verbose:\n        print(\"updating index in:\", dir_path)\n    index_path = join(dir_path, '.index.json')\n    if force:\n        index = {}\n    else:\n        try:\n            mode_dict = {'mode': 'r', 'encoding': 'utf-8'} if PY3 else {'mode': 'rb'}\n            with open(index_path, **mode_dict) as fi:\n                index = json.load(fi)\n        except (IOError, ValueError):\n            index = {}\n\n    files = set(fn for fn in os.listdir(dir_path) if fn.endswith('.tar.bz2'))\n    if any(fn.startswith('_license-') for fn in files):\n        sys.exit(\"\"\"\\\nError:\n    Indexing a copy of the Anaconda conda package channel is neither\n    necessary nor supported.  If you which to add your own packages,\n    you can do so by adding them to a separate channel.\n\"\"\")\n    for fn in files:\n        path = join(dir_path, fn)\n        if fn in index:\n            if check_md5:\n                if index[fn]['md5'] == md5_file(path):\n                    continue\n            elif index[fn]['mtime'] == getmtime(path):\n                continue\n        if verbose:\n            print('updating:', fn)\n        d = read_index_tar(path)\n        d.update(file_info(path))\n        index[fn] = d\n\n    for fn in files:\n        index[fn]['sig'] = '.' if isfile(join(dir_path, fn + '.sig')) else None\n\n    if remove:\n        # remove files from the index which are not on disk\n        for fn in set(index) - files:\n            if verbose:\n                print(\"removing:\", fn)\n            del index[fn]\n\n    # Deal with Python 2 and 3's different json module type reqs\n    mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}\n    with open(index_path, **mode_dict) as fo:\n        json.dump(index, fo, indent=2, sort_keys=True, default=str)\n\n    # --- new repodata\n    for fn in index:\n        info = index[fn]\n        for varname in 'arch', 'platform', 'mtime', 'ucs':\n            try:\n                del info[varname]\n            except KeyError:\n                pass\n\n        if 'requires' in info and 'depends' not in info:\n            info['depends'] = info['requires']\n\n    repodata = {'packages': index, 'info': {}}\n    write_repodata(repodata, dir_path)\n", "path": "conda_build/index.py"}], "after_files": [{"content": "'''\nFunctions related to creating repodata index files.\n'''\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport bz2\nimport sys\nimport json\nimport tarfile\nfrom os.path import isfile, join, getmtime\n\nfrom conda_build.utils import file_info\nfrom conda.compat import PY3\nfrom conda.utils import md5_file\n\n\ndef read_index_tar(tar_path):\n    \"\"\" Returns the index.json dict inside the given package tarball. \"\"\"\n    try:\n        with tarfile.open(tar_path) as t:\n            try:\n                return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))\n            except EOFError:\n                raise RuntimeError(\"Could not extract %s. File probably corrupt.\"\n                    % tar_path)\n            except OSError as e:\n                raise RuntimeError(\"Could not extract %s (%s)\" % (tar_path, e))\n    except tarfile.ReadError:\n        raise RuntimeError(\"Could not extract metadata from %s. File probably corrupt.\" % tar_path)\n\ndef write_repodata(repodata, dir_path):\n    \"\"\" Write updated repodata.json and repodata.json.bz2 \"\"\"\n    data = json.dumps(repodata, indent=2, sort_keys=True)\n    # strip trailing whitespace\n    data = '\\n'.join(line.rstrip() for line in data.split('\\n'))\n    # make sure we have newline at the end\n    if not data.endswith('\\n'):\n        data += '\\n'\n    with open(join(dir_path, 'repodata.json'), 'w') as fo:\n        fo.write(data)\n    with open(join(dir_path, 'repodata.json.bz2'), 'wb') as fo:\n        fo.write(bz2.compress(data.encode('utf-8')))\n\ndef update_index(dir_path, verbose=False, force=False, check_md5=False, remove=True):\n    \"\"\"\n    Update all index files in dir_path with changed packages.\n\n    :param verbose: Should detailed status messages be output?\n    :type verbose: bool\n    :param force: Whether to re-index all packages (including those that\n                  haven't changed) or not.\n    :type force: bool\n    :param check_md5: Whether to check MD5s instead of mtimes for determining\n                      if a package changed.\n    :type check_md5: bool\n    \"\"\"\n    if verbose:\n        print(\"updating index in:\", dir_path)\n    index_path = join(dir_path, '.index.json')\n    if force:\n        index = {}\n    else:\n        try:\n            mode_dict = {'mode': 'r', 'encoding': 'utf-8'} if PY3 else {'mode': 'rb'}\n            with open(index_path, **mode_dict) as fi:\n                index = json.load(fi)\n        except (IOError, ValueError):\n            index = {}\n\n    files = set(fn for fn in os.listdir(dir_path) if fn.endswith('.tar.bz2'))\n    if any(fn.startswith('_license-') for fn in files):\n        sys.exit(\"\"\"\\\nError:\n    Indexing a copy of the Anaconda conda package channel is neither\n    necessary nor supported.  If you which to add your own packages,\n    you can do so by adding them to a separate channel.\n\"\"\")\n    for fn in files:\n        path = join(dir_path, fn)\n        if fn in index:\n            if check_md5:\n                if index[fn]['md5'] == md5_file(path):\n                    continue\n            elif index[fn]['mtime'] == getmtime(path):\n                continue\n        if verbose:\n            print('updating:', fn)\n        d = read_index_tar(path)\n        d.update(file_info(path))\n        index[fn] = d\n\n    for fn in files:\n        index[fn]['sig'] = '.' if isfile(join(dir_path, fn + '.sig')) else None\n\n    if remove:\n        # remove files from the index which are not on disk\n        for fn in set(index) - files:\n            if verbose:\n                print(\"removing:\", fn)\n            del index[fn]\n\n    # Deal with Python 2 and 3's different json module type reqs\n    mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}\n    with open(index_path, **mode_dict) as fo:\n        json.dump(index, fo, indent=2, sort_keys=True, default=str)\n\n    # --- new repodata\n    for fn in index:\n        info = index[fn]\n        for varname in 'arch', 'platform', 'mtime', 'ucs':\n            try:\n                del info[varname]\n            except KeyError:\n                pass\n\n        if 'requires' in info and 'depends' not in info:\n            info['depends'] = info['requires']\n\n    repodata = {'packages': index, 'info': {}}\n    write_repodata(repodata, dir_path)\n", "path": "conda_build/index.py"}]}