'Build database index from scratch based on a directory layout.
Locks the DB if it isn\'t locked already.'

def reindex(self, directory_layout):

    def _read_suppress_error():
        try:
            if os.path.isfile(self._index_path):
                self._read_from_file(self._index_path)
        except CorruptDatabaseError as e:
            self._error = e
            self._data = {}
    transaction = WriteTransaction(self.lock, _read_suppress_error, self._write, _db_lock_timeout)
    with transaction:
        if self._error:
            tty.warn('Spack    database    was    corrupt.    Will    rebuild.    Error    was:', str(self._error))
            self._error = None
        old_data = self._data
        try:
            self._data = {}
            processed_specs = set()
            for spec in directory_layout.all_specs():
                tty.debug('RECONSTRUCTING    FROM    SPEC.YAML:    {0}'.format(spec))
                explicit = True
                if (old_data is not None):
                    old_info = old_data.get(spec.dag_hash())
                    if (old_info is not None):
                        explicit = old_info.explicit
                self._add(spec, directory_layout, explicit=explicit)
                processed_specs.add(spec)
            for (key, entry) in old_data.items():
                if (entry.spec in processed_specs):
                    msg = 'SKIPPING    RECONSTRUCTION    FROM    OLD    DB:    {0}'
                    msg += '    [already    reconstructed    from    spec.yaml]'
                    tty.debug(msg.format(entry.spec))
                    continue
                tty.debug('RECONSTRUCTING    FROM    OLD    DB:    {0}'.format(entry.spec))
                try:
                    layout = spack.store.layout
                    if entry.spec.external:
                        layout = None
                        install_check = True
                    else:
                        install_check = layout.check_installed(entry.spec)
                    if install_check:
                        kwargs = {'spec': entry.spec, 'directory_layout': layout, 'explicit': entry.explicit}
                        self._add(**kwargs)
                        processed_specs.add(entry.spec)
                except Exception as e:
                    tty.debug(e.message)
                    pass
            self._check_ref_counts()
        except:
            self._data = old_data
            raise
