def get_files_at_time(repository_url, to_date):
    """ Retrieve all the latest changes wrt files until the to_date,
    corresponding to the given repository.
    """
    query_files_at_time = (
        """
    {
        "size": 0,
        "aggs": {
            "file_stats": {
                "terms": {
                    "field": "file_path",
                    "size": 2147483647,
                    "order": {
                        "_key": "desc"
                    }
                },
                "aggs": {
                    "1": {
                        "top_hits": {
                            "size": 1,
                            "sort": [{
                                "metadata__updated_on": {
                                    "order": "desc"
                                }
                            }]
                        }
                    }
                }
            }
        },
        "query": {
            "bool": {
                "filter": [{
                    "term": {
                        "origin": "%s"
                    }
                },
                {
                    "range": {
                        "metadata__updated_on": {
                            "lte": "%s"
                        }
                    }
                }]
            }
        }
    }
    """
         % (repository_url, to_date))
    return query_files_at_time
