<commit_before>'''
Script to generate the file `plugins_index.txt` with information about pytest plugins taken directly 
from a live pypi server.

This will evolve to include test compatibility (pythons and pytest versions) information also.
'''
from collections import namedtuple
import datetime
from distutils.version import LooseVersion
import itertools
from optparse import OptionParser
import os
import sys
import xmlrpclib


#===================================================================================================
# iter_plugins
#===================================================================================================
def iter_plugins(client, search='pytest-'):
    '''
    Returns an iterator of (name, version) from pypi.
    
    :param client: xmlrpclib.ServerProxy
    :param search: package names to search for 
    '''
    for plug_data in client.search({'name' : search}):
        yield plug_data['name'], plug_data['version']


#===================================================================================================
# get_latest_versions
#===================================================================================================
def get_latest_versions(plugins):
    '''
    Returns an iterator of (name, version) from the given list of (name, version), but returning 
    only the latest version of the package. Uses distutils.LooseVersion to ensure compatibility
    with PEP386.
    '''
    plugins = [(name, LooseVersion(version)) for (name, version) in plugins]
    for name, grouped_plugins in itertools.groupby(plugins, key=lambda x: x[0]):
        name, loose_version = list(grouped_plugins)[-1]
        yield name, str(loose_version)
        
        
#===================================================================================================
# obtain_plugins_table
#===================================================================================================
def obtain_plugins_table(plugins, client):    
    '''
    Returns information to populate a table of plugins, their versions, authors, etc.
    
    The returned information is a list of columns of `ColumnData` namedtuples(text, link). Link
    can be None if the text for that column should not be linked to anything. 
    
    :param plugins: list of (name, version)
    :param client: xmlrpclib.ServerProxy
    
    '''
    rows = []
    ColumnData = namedtuple('ColumnData', 'text link')
    headers = ['Name', 'Version', 'Author', 'Summary']
    
    for package_name, version in plugins:
        release_data = client.release_data(package_name, version)
        row = (
            ColumnData(package_name, release_data['package_url']),
            ColumnData(version, release_data['release_url']),
            ColumnData(release_data['author'], release_data['author_email']),
            ColumnData(release_data['summary'], None),
        )
        assert len(row) == len(headers)
        rows.append(row)
        
    return headers, rows    


#===================================================================================================
# generate_plugins_index_from_table
#===================================================================================================
def generate_plugins_index_from_table(filename, headers, rows):
    '''
    Generates a RST file with the table data given.
     
    :param filename: output filename
    :param headers: see `obtain_plugins_table`
    :param rows: see `obtain_plugins_table`
    '''
    # creates a list of rows, each being a str containing appropriate column text and link
    table_texts = []
    for row in rows:
        column_texts = []
        for i, col_data in enumerate(row): 
            text = '`%s <%s>`_' % (col_data.text, col_data.link) if col_data.link else col_data.text
            column_texts.append(text)
        table_texts.append(column_texts)
        
    # compute max length of each column so we can build the rst table
    column_lengths = [len(x) for x in headers]
    for column_texts in table_texts:
        for i, row_text in enumerate(column_texts):
            column_lengths[i] = max(column_lengths[i], len(row_text) + 2)
    
    def get_row_limiter(char):
        return ' '.join(char * length for length in column_lengths)
    
    with file(filename, 'w') as f:
        # write welcome 
        print >> f, '.. _plugins_index:'
        print >> f
        print >> f, 'List of Third-Party Plugins'
        print >> f, '==========================='
        print >> f
        
        # table 
        print >> f, get_row_limiter('=')
        for i, header in enumerate(headers):
            print >> f, '{:^{fill}}'.format(header, fill=column_lengths[i]),
        print >> f
        print >> f, get_row_limiter('=')
        
        for column_texts in table_texts:
            for i, row_text in enumerate(column_texts):
                print >> f, '{:^{fill}}'.format(row_text, fill=column_lengths[i]),
            print >> f
        print >> f
        print >> f, get_row_limiter('=')
        print >> f
        
        print >> f, '*(Updated on %s)*' % _get_today_as_str()
        

#===================================================================================================
# _get_today_as_str
#===================================================================================================
def _get_today_as_str():
    '''
    internal. only exists so we can patch it in testing.
    '''
    return datetime.date.today().strftime('%Y-%m-%d')


#===================================================================================================
# generate_plugins_index
#===================================================================================================
def generate_plugins_index(client, filename):
    '''
    Generates an RST file with a table of the latest pytest plugins found in pypi. 
    
    :param client: xmlrpclib.ServerProxy
    :param filename: output filename
    '''
    plugins = get_latest_versions(iter_plugins(client))
    headers, rows = obtain_plugins_table(plugins, client)
    generate_plugins_index_from_table(filename, headers, rows)
    

#===================================================================================================
# main
#===================================================================================================
def main(argv):
    filename = os.path.join(os.path.dirname(__file__), 'plugins_index.txt')
    url = 'http://pypi.python.org/pypi'
    
    parser = OptionParser(description='Generates a restructured document of pytest plugins from PyPi')
    parser.add_option('-f', '--filename', default=filename, help='output filename [default: %default]')
    parser.add_option('-u', '--url', default=url, help='url of PyPi server to obtain data from [default: %default]')
    (options, _) = parser.parse_args(argv[1:])

    client = xmlrpclib.ServerProxy(options.url)
    generate_plugins_index(client, options.filename)
    print 'OK'
    return 0

#===================================================================================================
# main
#===================================================================================================
if __name__ == '__main__':
    sys.exit(main(sys.argv))<commit_msg>fixed 'PyPI' spelling<commit_after>'''
Script to generate the file `plugins_index.txt` with information about pytest plugins taken directly 
from a live PyPI server.

This will evolve to include test compatibility (pythons and pytest versions) information also.
'''
from collections import namedtuple
import datetime
from distutils.version import LooseVersion
import itertools
from optparse import OptionParser
import os
import sys
import xmlrpclib


#===================================================================================================
# iter_plugins
#===================================================================================================
def iter_plugins(client, search='pytest-'):
    '''
    Returns an iterator of (name, version) from PyPI.
    
    :param client: xmlrpclib.ServerProxy
    :param search: package names to search for 
    '''
    for plug_data in client.search({'name' : search}):
        yield plug_data['name'], plug_data['version']


#===================================================================================================
# get_latest_versions
#===================================================================================================
def get_latest_versions(plugins):
    '''
    Returns an iterator of (name, version) from the given list of (name, version), but returning 
    only the latest version of the package. Uses distutils.LooseVersion to ensure compatibility
    with PEP386.
    '''
    plugins = [(name, LooseVersion(version)) for (name, version) in plugins]
    for name, grouped_plugins in itertools.groupby(plugins, key=lambda x: x[0]):
        name, loose_version = list(grouped_plugins)[-1]
        yield name, str(loose_version)
        
        
#===================================================================================================
# obtain_plugins_table
#===================================================================================================
def obtain_plugins_table(plugins, client):    
    '''
    Returns information to populate a table of plugins, their versions, authors, etc.
    
    The returned information is a list of columns of `ColumnData` namedtuples(text, link). Link
    can be None if the text for that column should not be linked to anything. 
    
    :param plugins: list of (name, version)
    :param client: xmlrpclib.ServerProxy
    
    '''
    rows = []
    ColumnData = namedtuple('ColumnData', 'text link')
    headers = ['Name', 'Version', 'Author', 'Summary']
    
    for package_name, version in plugins:
        release_data = client.release_data(package_name, version)
        row = (
            ColumnData(package_name, release_data['package_url']),
            ColumnData(version, release_data['release_url']),
            ColumnData(release_data['author'], release_data['author_email']),
            ColumnData(release_data['summary'], None),
        )
        assert len(row) == len(headers)
        rows.append(row)
        
    return headers, rows    


#===================================================================================================
# generate_plugins_index_from_table
#===================================================================================================
def generate_plugins_index_from_table(filename, headers, rows):
    '''
    Generates a RST file with the table data given.
     
    :param filename: output filename
    :param headers: see `obtain_plugins_table`
    :param rows: see `obtain_plugins_table`
    '''
    # creates a list of rows, each being a str containing appropriate column text and link
    table_texts = []
    for row in rows:
        column_texts = []
        for i, col_data in enumerate(row): 
            text = '`%s <%s>`_' % (col_data.text, col_data.link) if col_data.link else col_data.text
            column_texts.append(text)
        table_texts.append(column_texts)
        
    # compute max length of each column so we can build the rst table
    column_lengths = [len(x) for x in headers]
    for column_texts in table_texts:
        for i, row_text in enumerate(column_texts):
            column_lengths[i] = max(column_lengths[i], len(row_text) + 2)
    
    def get_row_limiter(char):
        return ' '.join(char * length for length in column_lengths)
    
    with file(filename, 'w') as f:
        # write welcome 
        print >> f, '.. _plugins_index:'
        print >> f
        print >> f, 'List of Third-Party Plugins'
        print >> f, '==========================='
        print >> f
        
        # table 
        print >> f, get_row_limiter('=')
        for i, header in enumerate(headers):
            print >> f, '{:^{fill}}'.format(header, fill=column_lengths[i]),
        print >> f
        print >> f, get_row_limiter('=')
        
        for column_texts in table_texts:
            for i, row_text in enumerate(column_texts):
                print >> f, '{:^{fill}}'.format(row_text, fill=column_lengths[i]),
            print >> f
        print >> f
        print >> f, get_row_limiter('=')
        print >> f
        
        print >> f, '*(Updated on %s)*' % _get_today_as_str()
        

#===================================================================================================
# _get_today_as_str
#===================================================================================================
def _get_today_as_str():
    '''
    internal. only exists so we can patch it in testing.
    '''
    return datetime.date.today().strftime('%Y-%m-%d')


#===================================================================================================
# generate_plugins_index
#===================================================================================================
def generate_plugins_index(client, filename):
    '''
    Generates an RST file with a table of the latest pytest plugins found in PyPI. 
    
    :param client: xmlrpclib.ServerProxy
    :param filename: output filename
    '''
    plugins = get_latest_versions(iter_plugins(client))
    headers, rows = obtain_plugins_table(plugins, client)
    generate_plugins_index_from_table(filename, headers, rows)
    

#===================================================================================================
# main
#===================================================================================================
def main(argv):
    filename = os.path.join(os.path.dirname(__file__), 'plugins_index.txt')
    url = 'http://pypi.python.org/pypi'
    
    parser = OptionParser(description='Generates a restructured document of pytest plugins from PyPI')
    parser.add_option('-f', '--filename', default=filename, help='output filename [default: %default]')
    parser.add_option('-u', '--url', default=url, help='url of PyPI server to obtain data from [default: %default]')
    (options, _) = parser.parse_args(argv[1:])

    client = xmlrpclib.ServerProxy(options.url)
    generate_plugins_index(client, options.filename)
    print 'OK'
    return 0

#===================================================================================================
# main
#===================================================================================================
if __name__ == '__main__':
    sys.exit(main(sys.argv))
{'fraction_non_alphanumeric': 0.30534979423868314, 'fraction_numerical': 0.0010973936899862826, 'mean_word_length': 4.1000349772647775, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 65, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3913476', 'n_tokens_mistral': 3694, 'n_tokens_neox': 3499, 'n_words': 1001}