示例#1
0
def starred(username, token, sort, repository, message):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username yrqgithub --sort > README.md
    """
    if repository:
        if not token:
            click.secho('Error: create repository need set --token', fg='red')
            return
        file = BytesIO()
        sys.stdout = file
    else:
        file = None

    gh = GitHub(token=token)
    stars = gh.starred_by(username)
    click.echo(desc)
    repo_dict = {}

    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace(
            '\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
        repo_dict[language].append([s.name, s.html_url, description.strip()])

    if sort:
        repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))

    for language in repo_dict.keys():
        data = u'  - [{}](#{})'.format(language,
                                       '-'.join(language.lower().split()))
        click.echo(data)
    click.echo('')

    for language in repo_dict:
        click.echo('## {} \n'.format(language.replace('#', '# #')))
        for repo in repo_dict[language]:
            data = u'- [{}]({}) - {}'.format(*repo)
            click.echo(data)
        click.echo('')

    click.echo(license_.format(username=username))

    if file:
        try:
            rep = gh.repository(username, repository)
            readme = rep.readme()
            readme.update(message, file.getvalue())
        except NotFoundError:
            rep = gh.create_repository(repository,
                                       'A curated list of my GitHub stars!')
            rep.create_file('README.md', 'starred initial commit',
                            file.getvalue())
        click.launch(rep.html_url)
示例#2
0
文件: starred.py 项目: jiegec/starred
def starred(username, token, sort, repository, message):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username maguowei --sort > README.md
    """
    if repository:
        if not token:
            click.secho('Error: create repository need set --token', fg='red')
            return
        file = BytesIO()
        sys.stdout = file
    else:
        file = None

    gh = GitHub(token=token)
    stars = gh.starred_by(username)
    click.echo(desc)
    repo_dict = {}

    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace('\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
        repo_dict[language].append([s.full_name, s.name, s.html_url, description.strip(), s.homepage or ''])

    if sort:
        repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language], key=lambda l: l[1])

    for language in repo_dict.keys():
        data = u'  - [{}](#{})'.format(language, '-'.join(language.lower().split()))
        click.echo(data)
    click.echo('')

    for language in repo_dict:
        click.echo('## {} \n'.format(language.replace('#', '# #')))
        for repo in repo_dict[language]:
            data = u'* [{0}]({2}) - {3} [{4}]({4})'.format(*repo)
            click.echo(data)
        click.echo('')

    click.echo(license_.format(username=username))

    if file:
        rep = gh.repository(username, repository)
        if rep:
            readme = rep.readme()
            readme.update(message, file.getvalue())
        else:
            rep = gh.create_repository(repository, 'A curated list of my GitHub stars!')
            rep.create_file('README.md', 'starred initial commit', file.getvalue())
        click.launch(rep.html_url)
示例#3
0
def auto_create_repo(instance, **kwargs):
    try:
        userUUID = uuid.uuid4().hex

        # creating repo on GitHub
        gh = GitHub('*****@*****.**',
                    password='******')
        githubRepo = gh.create_repository(userUUID, description=u'',
                                          homepage=u'',
                                          private=False,
                                          has_issues=True,
                                          has_wiki=True,
                                          auto_init=True,
                                          gitignore_template=u'')
        githubRepo.create_blob('hello', 'utf-8')
        githubRepo.create_commit('first commit', '', '')

        # creating local repo
        repoPath = 'repos/' + userUUID
        UserProfile(user=instance, uuid=userUUID)
        EG.init_repo(repoPath, bare=False)

        # creating workspace in local repo
        workspace = EG.workspace(repoPath,
                                 index_prefix='',
                                 es={'urls': ['http://localhost:9200']})

        # pushing local repo to GitHub repo
        workspace.repo.create_remote('origin', githubRepo.html_url)
        repo = workspace.repo
        remote = repo.remote()
        remote.fetch()
        remote_master = remote.refs.master
        remote.push(remote_master.remote_head)
    except ValueError:
        raise
        workspace.refresh_index()
示例#4
0
文件: starred.py 项目: tqdv/starred
def starred(username, token, sort, repository, message, output, http_proxy,
            https_proxy, launch, type):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username 1132719438 --output README.md
    """
    if output.strip():
        output = output.strip()
        output_path = os.path.split(output)[0]
        if output_path and not os.path.isdir(output_path):
            os.makedirs(output_path)
        output_file = open(output, "w", encoding='utf-8')
    else:
        output_file = None

    if repository:
        if not token:
            click.secho('Error: create repository need set --token',
                        fg='red',
                        file=sys.stderr)
            return
        repo_file = BytesIO()
        sys.stdout = repo_file
        # do not output to file when update repository
        output_file = None
    else:
        repo_file = None

    try:
        gh = GitHub(token=token)
        if http_proxy:
            gh.session.proxies['http://'] = http_proxy
            if https_proxy:
                gh.session.proxies['https://'] = https_proxy
            else:
                gh.session.proxies['https://'] = http_proxy

        stars = gh.starred_by(username)
    except ForbiddenError as e:
        click.secho('Error: talk to Github failed: {}'.format(e),
                    fg='red',
                    file=sys.stderr)
        return
    today = str(datetime.date.today())
    month = datetime.date.today().strftime('%Y%m')

    repo_dict = {}
    new_dict = {}

    # starred order
    star_order = 0
    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace(
            '\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
        repo_dict[language].append([
            s.name, s.html_url,
            description.strip(), s.owner.login, s.stargazers_count, star_order
        ])
        if language not in new_dict:
            new_dict[language] = []
        new_dict[language].append([s.name, s.html_url])
        star_order += 1

    repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))
    new_dict = OrderedDict(sorted(new_dict.items(), key=lambda l: l[0]))

    # load prev repo dict and compare with new repo dict
    save_pkl = True
    cur_path = os.path.split(os.path.realpath(__file__))[0]
    repo_pkl_path = os.path.join(cur_path, 'starred-repo.pkl')
    if os.path.isfile(repo_pkl_path):
        with open(repo_pkl_path, 'rb') as file:
            old_dict = pickle.load(file, encoding='utf-8')
        if operator.eq(old_dict, new_dict):
            save_pkl = False
            if repo_file:
                click.secho(
                    'Error: starred repositories not change in {}'.format(
                        today),
                    fg='red',
                    file=sys.stderr)
                return

    if save_pkl:
        with open(repo_pkl_path, 'wb') as file:
            pickle.dump(new_dict, file)

    total = 0
    # sort by language and date
    if sort == 'date':
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[5])
            total += len(repo_dict[language])
    # sort by language and name
    elif sort == 'name':
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[0])
            total += len(repo_dict[language])
    # sort by language and stars
    else:
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[4],
                                         reverse=True)
            total += len(repo_dict[language])

    # desc
    count_badge_url = count_badge.format(count=total, color='green')
    date_badge_url = date_badge.format(today=today.replace('-', '--'),
                                       color='blue')
    click.echo(desc.format(badge_url=badge_url,
                           awesome_url=awesome_url,
                           github_url=github_url,
                           count_badge_url=count_badge_url,
                           date_badge_url=date_badge_url),
               file=output_file)

    # contents
    title_dict = {}
    for language in repo_dict.keys():
        title = '{} ({})'.format(language, len(repo_dict[language]))
        title_url = title2url(title)
        if title_url not in title_dict:
            title_dict[title_url] = 1
        else:
            cnt = title_dict[title_url]
            title_dict[title_url] += 1
            title_url = title_url + '-' + str(cnt)

        data = u'  - [{}](#{})'.format(title, title_url)
        click.echo(data, file=output_file)
    click.echo('', file=output_file)

    info_dict = {}
    for language in repo_dict:
        info_dict[language] = [
            [
                index + 1,  # index
                '[{}]({})'.format(repo[0], repo[1]),  # name with url
                repo[2],  # description
                repo[3],  # owner
                repo[4]
            ]  # stars
            for index, repo in enumerate(repo_dict[language])
        ]

    info_dict = OrderedDict(sorted(info_dict.items(), key=lambda l: l[0]))

    # repo
    for language in info_dict:
        count = len(info_dict[language])
        info_dict[language].insert(
            0, ['', 'Name', 'Description', 'Owner', 'Stars'])
        click.echo('## {} ({}) \n'.format(language, count), file=output_file)
        if type == 'table':
            table = GithubFlavoredMarkdownTable(info_dict[language])
            click.echo(table.table, file=output_file)
        else:
            for repo in repo_dict[language]:
                data = u'- [{}]({}) - {}'.format(*repo)
                click.echo(data, file=output_file)
        click.echo('', file=output_file)

    # license
    click.echo(license_.format(username=username), file=output_file)

    if repo_file:
        if not message:
            message = 'Add starred {}'.format(today)

        try:
            rep = gh.repository(username, repository)
            try:
                rep.file_contents('/Archives/{}/README-{}.md'.format(
                    month, today))
                click.secho(
                    'Error: already commit [/Archives/{}/README-{}.md]'.format(
                        month, today),
                    fg='red',
                    file=sys.stderr)
            except NotFoundError:
                readme = rep.readme()
                readme.update(message, repo_file.getvalue())
                rep.create_file(
                    'Archives/{}/README-{}.md'.format(month, today),
                    'Archive starred {}'.format(today), repo_file.getvalue())
        except NotFoundError:
            rep = gh.create_repository(repository,
                                       'A curated list of my GitHub stars!')
            rep.create_file('README.md', 'Add starred {}'.format(today),
                            repo_file.getvalue())
            rep.create_file('Archives/{}/README-{}.md'.format(month, today),
                            'Archive starred {}'.format(today),
                            repo_file.getvalue())
        if launch:
            click.launch(rep.html_url)
示例#5
0
def starred(username, token, sort, repository, message, format):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username ntk148v --sort > README.md
    """
    if repository:
        if not token:
            click.secho('Error: create repository need set --token', fg='red')
            return
        file = BytesIO()
        sys.stdout = file
    else:
        file = None

    gh = GitHub(token=token)
    user = gh.user(username)
    stars = gh.starred_by(username)
    click.echo(desc)
    repo_dict = {}
    # Just a dict to store index
    repo_num_dict = {}

    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace(
            '\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
            repo_num_dict[language] = 1
        repo_dict[language].append(
            [repo_num_dict[language], s.name, s.html_url,
             description.strip()])
        repo_num_dict[language] += 1

    if sort:
        repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))

    for language in repo_dict.keys():
        data = u'  - [{}](#{})'.format(language,
                                       '-'.join(language.lower().split()))
        click.echo(data)
    click.echo('')

    for language in repo_dict:
        click.echo('## {} \n'.format(language.replace('#', '# #')))
        if format == 'table':
            writer = MarkdownTableWriter(
                headers=['Index', 'Name', 'Repository URL', 'Description'],
                value_matrix=repo_dict[language],
                margin=1)
            click.echo(writer.dumps())
        else:
            for repo in repo_dict[language]:
                data = u'{}. [{}]({}) - {}'.format(*repo)
                click.echo(data)
        click.echo('')

    click.echo(license_.format(username=username))

    if file:
        try:
            rep = gh.repository(username, repository)
            readme = rep.readme()
            readme.update(message,
                          file.getvalue(),
                          author={
                              'name': user.name,
                              'email': user.email
                          })
        except NotFoundError:
            rep = gh.create_repository(repository,
                                       'A curated list of my GitHub stars!')
            rep.create_file('README.md',
                            'starred initial commit',
                            file.getvalue(),
                            author={
                                'name': user.name,
                                'email': user.email
                            })
        click.launch(rep.html_url)