We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
UnboundLocalError with --skip-existing and --no-locking flags
Hit this today on conda-build 2.1.2. Also tried with the tip of master and I get the same result.  For reproduciblity, this is the output for trying to build the conda.recipe folder inside of conda-build itself:

```
$ conda build conda.recipe --no-locking --skip-existing                 master :: 1h :: ⬢
Cloning into '/home/edill/miniconda/conda-bld/conda.recipe_1485803296268/work'...
done.
checkout: 'HEAD'
Your branch is up-to-date with 'origin/_conda_cache_origin_head'.
==> git log -n1 <==

commit 6922ec3ed1afc287a4cd7f3872572f2bef89d892
Merge: 837fbc8 c82ea9b
Author: Mike Sarahan <msarahan@gmail.com>
Date:   Mon Jan 30 11:38:01 2017 -0600

    Merge pull request #1704 from jerowe/feature/fix-perl-build

    adding some fixes to cpan skeleton


==> git describe --tags --dirty <==

2.1.2-20-g6922ec3


==> git status <==

On branch _conda_cache_origin_head
Your branch is up-to-date with 'origin/_conda_cache_origin_head'.

nothing to commit, working directory clean


updating index in: /home/edill/miniconda/conda-bld/linux-64
Traceback (most recent call last):
  File "/home/edill/miniconda/bin/conda-build", line 11, in <module>
    load_entry_point('conda-build', 'console_scripts', 'conda-build')()
  File "/home/edill/dev/conda/conda-build/conda_build/cli/main_build.py", line 322, in main
    execute(sys.argv[1:])
  File "/home/edill/dev/conda/conda-build/conda_build/cli/main_build.py", line 313, in execute
    noverify=args.no_verify)
  File "/home/edill/dev/conda/conda-build/conda_build/api.py", line 97, in build
    need_source_download=need_source_download, config=config)
  File "/home/edill/dev/conda/conda-build/conda_build/build.py", line 1478, in build_tree
    config=config)
  File "/home/edill/dev/conda/conda-build/conda_build/build.py", line 928, in build
    package_exists = is_package_built(m, config)
  File "/home/edill/dev/conda/conda-build/conda_build/build.py", line 1633, in is_package_built
    update_index(d, config, could_be_mirror=False)
  File "/home/edill/dev/conda/conda-build/conda_build/index.py", line 83, in update_index
    with try_acquire_locks(locks, config.timeout):
UnboundLocalError: local variable 'locks' referenced before assignment
```

And some debug info

```
$ conda info 
Current conda install:

               platform : linux-64
          conda version : 4.2.13
       conda is private : False
      conda-env version : 4.2.13
    conda-build version : 2.1.2+20.g6922ec3
         python version : 3.5.3.final.0
       requests version : 2.13.0
       root environment : /home/edill/miniconda  (writable)
    default environment : /home/edill/miniconda
       envs directories : /home/edill/miniconda/envs
          package cache : /home/edill/miniconda/pkgs
           channel URLs : ...
            config file : /home/edill/.condarc
           offline mode : 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, get_lock, try_acquire_locks
15 from .conda_interface import PY3, md5_file
16 
17 
18 def read_index_tar(tar_path, config, lock):
19     """ Returns the index.json dict inside the given package tarball. """
20     if config.locking:
21         locks = [lock]
22     with try_acquire_locks(locks, config.timeout):
23         with tarfile.open(tar_path) as t:
24             try:
25                 return json.loads(t.extractfile('info/index.json').read().decode('utf-8'))
26             except EOFError:
27                 raise RuntimeError("Could not extract %s. File probably corrupt."
28                     % tar_path)
29             except OSError as e:
30                 raise RuntimeError("Could not extract %s (%s)" % (tar_path, e))
31             except tarfile.ReadError:
32                 raise RuntimeError("Could not extract metadata from %s. "
33                                 "File probably corrupt." % tar_path)
34 
35 
36 def write_repodata(repodata, dir_path, lock, config=None):
37     """ Write updated repodata.json and repodata.json.bz2 """
38     if not config:
39         import conda_build.config
40         config = conda_build.config.config
41     if config.locking:
42         locks = [lock]
43     with try_acquire_locks(locks, config.timeout):
44         data = json.dumps(repodata, indent=2, sort_keys=True)
45         # strip trailing whitespace
46         data = '\n'.join(line.rstrip() for line in data.splitlines())
47         # make sure we have newline at the end
48         if not data.endswith('\n'):
49             data += '\n'
50         with open(join(dir_path, 'repodata.json'), 'w') as fo:
51             fo.write(data)
52         with open(join(dir_path, 'repodata.json.bz2'), 'wb') as fo:
53             fo.write(bz2.compress(data.encode('utf-8')))
54 
55 
56 def update_index(dir_path, config, force=False, check_md5=False, remove=True, lock=None,
57                  could_be_mirror=True):
58     """
59     Update all index files in dir_path with changed packages.
60 
61     :param verbose: Should detailed status messages be output?
62     :type verbose: bool
63     :param force: Whether to re-index all packages (including those that
64                   haven't changed) or not.
65     :type force: bool
66     :param check_md5: Whether to check MD5s instead of mtimes for determining
67                       if a package changed.
68     :type check_md5: bool
69     """
70 
71     if config.verbose:
72         print("updating index in:", dir_path)
73     index_path = join(dir_path, '.index.json')
74     if not os.path.isdir(dir_path):
75         os.makedirs(dir_path)
76 
77     if not lock:
78         lock = get_lock(dir_path)
79 
80     if config.locking:
81         locks = [lock]
82 
83     with try_acquire_locks(locks, config.timeout):
84         if force:
85             index = {}
86         else:
87             try:
88                 mode_dict = {'mode': 'r', 'encoding': 'utf-8'} if PY3 else {'mode': 'rb'}
89                 with open(index_path, **mode_dict) as fi:
90                     index = json.load(fi)
91             except (IOError, ValueError):
92                 index = {}
93 
94         files = set(fn for fn in os.listdir(dir_path) if fn.endswith('.tar.bz2'))
95         if could_be_mirror and any(fn.startswith('_license-') for fn in files):
96             sys.exit("""\
97     Error:
98         Indexing a copy of the Anaconda conda package channel is neither
99         necessary nor supported.  If you wish to add your own packages,
100         you can do so by adding them to a separate channel.
101     """)
102         for fn in files:
103             path = join(dir_path, fn)
104             if fn in index:
105                 if check_md5:
106                     if index[fn]['md5'] == md5_file(path):
107                         continue
108                 elif index[fn]['mtime'] == getmtime(path):
109                     continue
110             if config.verbose:
111                 print('updating:', fn)
112             d = read_index_tar(path, config, lock=lock)
113             d.update(file_info(path))
114             index[fn] = d
115 
116         for fn in files:
117             index[fn]['sig'] = '.' if isfile(join(dir_path, fn + '.sig')) else None
118 
119         if remove:
120             # remove files from the index which are not on disk
121             for fn in set(index) - files:
122                 if config.verbose:
123                     print("removing:", fn)
124                 del index[fn]
125 
126         # Deal with Python 2 and 3's different json module type reqs
127         mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}
128         with open(index_path, **mode_dict) as fo:
129             json.dump(index, fo, indent=2, sort_keys=True, default=str)
130 
131         # --- new repodata
132         for fn in index:
133             info = index[fn]
134             for varname in 'arch', 'platform', 'mtime', 'ucs':
135                 try:
136                     del info[varname]
137                 except KeyError:
138                     pass
139 
140             if 'requires' in info and 'depends' not in info:
141                 info['depends'] = info['requires']
142 
143         repodata = {'packages': index, 'info': {}}
144         write_repodata(repodata, dir_path, lock=lock, config=config)
145
```
--- 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
@@ -77,8 +77,9 @@
     if not lock:
         lock = get_lock(dir_path)
 
+    locks = []
     if config.locking:
-        locks = [lock]
+        locks.append(lock)
 
     with try_acquire_locks(locks, config.timeout):
         if force:

{"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@@ -77,8 +77,9 @@\n     if not lock:\n         lock = get_lock(dir_path)\n \n+    locks = []\n     if config.locking:\n-        locks = [lock]\n+        locks.append(lock)\n \n     with try_acquire_locks(locks, config.timeout):\n         if force:\n", "issue": "UnboundLocalError with --skip-existing and --no-locking flags\nHit this today on conda-build 2.1.2. Also tried with the tip of master and I get the same result.  For reproduciblity, this is the output for trying to build the conda.recipe folder inside of conda-build itself:\r\n\r\n```\r\n$ conda build conda.recipe --no-locking --skip-existing                 master :: 1h :: \u2b22\r\nCloning into '/home/edill/miniconda/conda-bld/conda.recipe_1485803296268/work'...\r\ndone.\r\ncheckout: 'HEAD'\r\nYour branch is up-to-date with 'origin/_conda_cache_origin_head'.\r\n==> git log -n1 <==\r\n\r\ncommit 6922ec3ed1afc287a4cd7f3872572f2bef89d892\r\nMerge: 837fbc8 c82ea9b\r\nAuthor: Mike Sarahan <msarahan@gmail.com>\r\nDate:   Mon Jan 30 11:38:01 2017 -0600\r\n\r\n    Merge pull request #1704 from jerowe/feature/fix-perl-build\r\n\r\n    adding some fixes to cpan skeleton\r\n\r\n\r\n==> git describe --tags --dirty <==\r\n\r\n2.1.2-20-g6922ec3\r\n\r\n\r\n==> git status <==\r\n\r\nOn branch _conda_cache_origin_head\r\nYour branch is up-to-date with 'origin/_conda_cache_origin_head'.\r\n\r\nnothing to commit, working directory clean\r\n\r\n\r\nupdating index in: /home/edill/miniconda/conda-bld/linux-64\r\nTraceback (most recent call last):\r\n  File \"/home/edill/miniconda/bin/conda-build\", line 11, in <module>\r\n    load_entry_point('conda-build', 'console_scripts', 'conda-build')()\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/cli/main_build.py\", line 322, in main\r\n    execute(sys.argv[1:])\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/cli/main_build.py\", line 313, in execute\r\n    noverify=args.no_verify)\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/api.py\", line 97, in build\r\n    need_source_download=need_source_download, config=config)\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/build.py\", line 1478, in build_tree\r\n    config=config)\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/build.py\", line 928, in build\r\n    package_exists = is_package_built(m, config)\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/build.py\", line 1633, in is_package_built\r\n    update_index(d, config, could_be_mirror=False)\r\n  File \"/home/edill/dev/conda/conda-build/conda_build/index.py\", line 83, in update_index\r\n    with try_acquire_locks(locks, config.timeout):\r\nUnboundLocalError: local variable 'locks' referenced before assignment\r\n```\r\n\r\nAnd some debug info\r\n\r\n```\r\n$ conda info \r\nCurrent conda install:\r\n\r\n               platform : linux-64\r\n          conda version : 4.2.13\r\n       conda is private : False\r\n      conda-env version : 4.2.13\r\n    conda-build version : 2.1.2+20.g6922ec3\r\n         python version : 3.5.3.final.0\r\n       requests version : 2.13.0\r\n       root environment : /home/edill/miniconda  (writable)\r\n    default environment : /home/edill/miniconda\r\n       envs directories : /home/edill/miniconda/envs\r\n          package cache : /home/edill/miniconda/pkgs\r\n           channel URLs : ...\r\n            config file : /home/edill/.condarc\r\n           offline mode : False\r\n```\r\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, get_lock, try_acquire_locks\nfrom .conda_interface import PY3, md5_file\n\n\ndef read_index_tar(tar_path, config, lock):\n    \"\"\" Returns the index.json dict inside the given package tarball. \"\"\"\n    if config.locking:\n        locks = [lock]\n    with try_acquire_locks(locks, config.timeout):\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. \"\n                                \"File probably corrupt.\" % tar_path)\n\n\ndef write_repodata(repodata, dir_path, lock, config=None):\n    \"\"\" Write updated repodata.json and repodata.json.bz2 \"\"\"\n    if not config:\n        import conda_build.config\n        config = conda_build.config.config\n    if config.locking:\n        locks = [lock]\n    with try_acquire_locks(locks, config.timeout):\n        data = json.dumps(repodata, indent=2, sort_keys=True)\n        # strip trailing whitespace\n        data = '\\n'.join(line.rstrip() for line in data.splitlines())\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\n\ndef update_index(dir_path, config, force=False, check_md5=False, remove=True, lock=None,\n                 could_be_mirror=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\n    if config.verbose:\n        print(\"updating index in:\", dir_path)\n    index_path = join(dir_path, '.index.json')\n    if not os.path.isdir(dir_path):\n        os.makedirs(dir_path)\n\n    if not lock:\n        lock = get_lock(dir_path)\n\n    if config.locking:\n        locks = [lock]\n\n    with try_acquire_locks(locks, config.timeout):\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 could_be_mirror and any(fn.startswith('_license-') for fn in files):\n            sys.exit(\"\"\"\\\n    Error:\n        Indexing a copy of the Anaconda conda package channel is neither\n        necessary nor supported.  If you wish 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 config.verbose:\n                print('updating:', fn)\n            d = read_index_tar(path, config, lock=lock)\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 config.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, lock=lock, config=config)\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, get_lock, try_acquire_locks\nfrom .conda_interface import PY3, md5_file\n\n\ndef read_index_tar(tar_path, config, lock):\n    \"\"\" Returns the index.json dict inside the given package tarball. \"\"\"\n    if config.locking:\n        locks = [lock]\n    with try_acquire_locks(locks, config.timeout):\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. \"\n                                \"File probably corrupt.\" % tar_path)\n\n\ndef write_repodata(repodata, dir_path, lock, config=None):\n    \"\"\" Write updated repodata.json and repodata.json.bz2 \"\"\"\n    if not config:\n        import conda_build.config\n        config = conda_build.config.config\n    if config.locking:\n        locks = [lock]\n    with try_acquire_locks(locks, config.timeout):\n        data = json.dumps(repodata, indent=2, sort_keys=True)\n        # strip trailing whitespace\n        data = '\\n'.join(line.rstrip() for line in data.splitlines())\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\n\ndef update_index(dir_path, config, force=False, check_md5=False, remove=True, lock=None,\n                 could_be_mirror=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\n    if config.verbose:\n        print(\"updating index in:\", dir_path)\n    index_path = join(dir_path, '.index.json')\n    if not os.path.isdir(dir_path):\n        os.makedirs(dir_path)\n\n    if not lock:\n        lock = get_lock(dir_path)\n\n    locks = []\n    if config.locking:\n        locks.append(lock)\n\n    with try_acquire_locks(locks, config.timeout):\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 could_be_mirror and any(fn.startswith('_license-') for fn in files):\n            sys.exit(\"\"\"\\\n    Error:\n        Indexing a copy of the Anaconda conda package channel is neither\n        necessary nor supported.  If you wish 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 config.verbose:\n                print('updating:', fn)\n            d = read_index_tar(path, config, lock=lock)\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 config.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, lock=lock, config=config)\n", "path": "conda_build/index.py"}]}