'Reset tool version lineage for those changeset revisions that include valid tools.'

def reset_all_tool_versions(self, repo):

    encoded_repository_id = self.app.security.encode_id(self.repository.id)
    changeset_revisions_that_contain_tools = []
    for changeset in repo.changelog:
        changeset_revision = str(repo.changectx(changeset))
        repository_metadata = metadata_util.get_repository_metadata_by_changeset_revision(self.app, encoded_repository_id, changeset_revision)
        if repository_metadata:
            metadata = repository_metadata.metadata
            if metadata:
                if metadata.get('tools', None):
                    changeset_revisions_that_contain_tools.append(changeset_revision)
    for (index, changeset_revision) in enumerate(changeset_revisions_that_contain_tools):
        tool_versions_dict = {}
        repository_metadata = metadata_util.get_repository_metadata_by_changeset_revision(self.app, encoded_repository_id, changeset_revision)
        metadata = repository_metadata.metadata
        tool_dicts = metadata['tools']
        if (index == 0):
            for tool_dict in tool_dicts:
                tool_versions_dict[tool_dict['guid']] = tool_dict['id']
        else:
            for tool_dict in tool_dicts:
                parent_id = self.get_parent_id(encoded_repository_id, tool_dict['id'], tool_dict['version'], tool_dict['guid'], changeset_revisions_that_contain_tools[0:index])
                tool_versions_dict[tool_dict['guid']] = parent_id
        if tool_versions_dict:
            repository_metadata.tool_versions = tool_versions_dict
            self.sa_session.add(repository_metadata)
            self.sa_session.flush()
