from github import Github, GithubException
from decouple import config
import base64

g = Github(config('GITHUB_USER'), config('GITHUB_PASS'))


def get_user_info(user_link):
    num_of_repos = 0
    repos = []
    followers = 0
    try:
        username = user_link.strip('/').split("/")[-1]
        user = g.get_user(username)
        for r in user.get_repos():
            temp = []
            temp.append(r.name)
            temp.append(r.language)
            try:
                temp.append(base64.b64decode(r.get_readme().content))
            except GithubException:
                temp.append('')
            repos.append(temp)
            num_of_repos += 1
        followers = user.followers
    except GithubException:
        print("No user found")
        return None
    return {
        "num_of_repos": num_of_repos,
        "repos": repos,
Ejemplo n.º 2
0
def remove():

    init()

    if len(sys.argv) == 1:
        general_usage()
        sys.exit(0)

    elif len(sys.argv) > 2:
        print(f"Syntax Error: Command requires only one argument, {int(len(sys.argv) - 1)} were given.")
        general_usage()
        sys.exit(1)

    # Log in
    token = os.environ.get("PWFA-Token")
    g = Github(token)
    user = g.get_user()
    login = user.login

    list = ["-l", "--list"]

    # Remove remote repository

    # remove -l, --list
    if str(sys.argv[1]) in list:
        repo_number = 0
        print()
        for repo in user.get_repos():
            repo_number += 1
            print(f"  {repo_number}.   {repo.name}")
        print()
        sys.exit(0)
    else:
        try:

            git_url = "https://github.com/"

            # remove -X
            if (
                str(sys.argv[1]).startswith("-") and
                str(sys.argv[1])[1:].isnumeric()
               ):
                passed_int = int(str(sys.argv[1])[1:])
                local_repo_name = user.get_repos()[passed_int - 1].name
                repo_url =  "{}{}".format(git_url,
                                          user.get_repos()[passed_int - 1].full_name)

                # Confirm deletion
                if ask_delete_repo(repo_url):
                    user.get_repos()[passed_int - 1].delete()
                    print(f"Deleted repository {repo_url}")
                else:
                    print("Remote repository not deleted.")
            else:
            # remove repoName
                passed_str = str(sys.argv[1])
                local_repo_name = passed_str
                repo_url = "{}{}".format(git_url,
                                         user.get_repo(passed_str).full_name)

                # Confirm deletion
                if ask_delete_repo(repo_url):
                    user.get_repo(passed_str).delete()
                    print(f"Deleted repository {repo_url}")
                else:
                    print("Remote repository not deleted.")
        except:
            # TODO Run refactor local to test other possible repo name
            print(f"Naming Error: Error in finding remote repository \"{local_repo_name}\"")
            sys.exit(1)

    # Move on to local or exit
    if not ask_continue_local():
        sys.exit(0)

    # Remove local repository

    path = os.environ.get("PWFA-Path")

    # Search local repos with dashes
    if os.path.isdir(f"{path}\\\\{local_repo_name}"):

        path += "\\\\" + local_repo_name

        # Delete if selected
        if ask_delete_repo(local_repo_name):
            remove_local_directory(path, local_repo_name)
        else:
            print("Local repository not deleted.\n")

    # Search local repos with spaces
    elif os.path.isdir(f"{path}\\{refactor_local(local_repo_name)}"):

        local_repo_name = refactor_local(local_repo_name)
        path += "\\\\" + local_repo_name

        # Delete if selected
        if ask_delete_repo(path):
            remove_local_directory(path, local_repo_name)
        else:
            print("Local repository not deleted.\n")

    # Local repository not found
    else:
        print("A directory with that name could not be found.")
from github import Github

baseUrl = 'https://raw.githubusercontent.com/'

g = Github('*****@*****.**', '19950525hansani')
repository = g.get_repo('Nimesha-Hansani/TestRepo-CDAP')
branches = repository.get_branches()

for br in branches:
    headCommit = br.commit.sha

    commits = repository.get_commits(headCommit)
    for com in commits:
        commitDateTime = com.commit.author.date
        print(commitDateTime)

        tree = repository.get_git_tree(com.sha).tree

        for tr in tree:
            try:
                if (tr.type == "tree"):

                    treeContent = repository.get_contents(tr.path)
                    while len(treeContent) > 0:
                        file_content = treeContent.pop(0)

                        if file_content.type == "dir":
                            treeContent.extend(
                                repository.get_contents(file_content.path))

                        else:
Ejemplo n.º 4
0
print(f"Using range: {tags}")

# Local git clone
g = git.Git('.')
g.fetch()
project = re.compile(r'slaclab/(?P<name>.*?).git').search(g.remote('get-url','origin')).group('name')

user = args.user
password = None

if user is not None:
    password = getpass("Password for github: ")

# Git server
gh = Github(user,password)
repo = gh.get_repo(f'slaclab/{project}')

loginfo = g.log(tags,'--grep','Merge pull request')

records = []
entry = {}

#print("# Pull Requests")

# Parse the log entries
for line in loginfo.splitlines():

    if line.startswith('Author:'):
        entry['Author'] = line[7:].lstrip()
#!/usr/bin/env python3

from github import Github

# provide access token
g = Github('insert-token-here')

org = g.get_organization('ros-industrial')

proj = [
    b for b in org.get_projects()
    if b.name == 'World ROS-Industrial Day 2019 - Issue board'
][0]

#print (proj.get_columns())

col = [c for c in proj.get_columns() if c.name == 'unassigned'][0]

# remove the label from all unassigned items
for uc in col.get_cards():
    content = uc.get_content()
    print('Removing label from {} ..'.format(content.url))
    content.remove_from_labels('wrid19')
Ejemplo n.º 6
0
import glob
from urllib.request import urlretrieve

import yaml
from flask import Flask
from flask import request
from github import Github
from flask import render_template


GITHUB_ACCESS_TOKEN = os.environ.get('GITHUB_ACCESS_TOKEN', '')

app = Flask(__name__, static_url_path='/static')
app.config['FREEZER_DESTINATION'] = 'docs'

g = Github(GITHUB_ACCESS_TOKEN)

def check_pr(pr):
    print(pr)
    files = [file for file in pr.get_files()]
    
    # check number of file
    print(files) 
    if len(files) != 1:
        return False

    # check file status
    print(files[0].status)
    if files[0].status != 'added':
        print(files[0].status)
        return False
Ejemplo n.º 7
0
def gh_session():
    """Returns a PyGithub session."""
    if gh_access_token:
        return Github(gh_access_token)

    return Github()
Ejemplo n.º 8
0
def create():
    user = Github(username, password).get_user()
    repo = user.create_repo(sys.argv[1])
    print("Succesfully created repository {}".format(sys.argv[1]))
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 16:18:51 2018

@author: Aru
"""

from github import Github
import pandas as pd
import socket
g = Github("9a943c0128ea8806c6e364701aa106fa4ea3ab2c")
dir(g)

#df = pd.read_csv("F:\Twitter+GitHub.csv")
#print(df.head(5))
#print(df.columns)
#new = df["GitHub Url"].str.split("https://github.com/", n=1, expand = True)
#print(new.head())
#df["Repository Path"] = new[1]
#print(df.head())
#df.to_csv("F:\Twitter+GitHub_New.csv", index = False)

if (socket.gethostname() == 'c063144'):
    path = 'C:\\Users\\vivek4\\Downloads\\gitterFiles\\'
else:
    path = 'F:\\'
# A copy of following file is available in google drive at
# Github-Gitter Project>OpenCollective>arundhati_files
newdf = pd.read_csv(path + "Twitter+GitHub_New1.csv")

commits = []
import os
import time
from datetime import datetime

import requests
import xlrd
import xlsxwriter
from requests.auth import HTTPBasicAuth
from github import Github
from colorama import Fore, Back, Style
import zlib

g_counter = 0
username = [ 'soghac']
password = [ '8cfc66cbda6c52ca0f7c4866e0b909fa18d31cdb']
g = Github(username[g_counter % 3], password[g_counter % 3])


class Repository:
    parent_commits_dict = dict()
    parent_pulls_requests = dict()
    parent_pulls_requests_authors = dict()
    list_authors = set()
    june_2019 = datetime.strptime('2019-June', '%Y-%B')

    @staticmethod
    def get_full_name_from_url(url):
        return url.replace('https://api.github.com/repos/', '')

    @staticmethod
    def convert_message_to_number(message):
    def repo_info(full_name):
        try:
            dict_total = dict()
            global g, g_counter, username, password
            repo = g.get_repo(full_name)
            g_counter += 1
            g = Github(username[g_counter % 3], password[g_counter % 3])
            parent_commit = None
            parent_pull_request = None
            parent_pull_request_author = None
            parent_full_name = None
            len_parent_commit = None
            if repo.parent:

                print("----------------------------this repository has a parent------------------------------------")
                parent_full_name = repo.parent.full_name
                if Repository.parent_commits_dict.get(parent_full_name):

                    parent_commit = Repository.parent_commits_dict.get(parent_full_name)
                    parent_pull_request = Repository.parent_pulls_requests.get(parent_full_name)
                    parent_pull_request_author = Repository.parent_pulls_requests_authors.get(parent_full_name)

                else:

                    parent_commit = Repository.get_commits_date(parent_full_name)
                    Repository.parent_commits_dict[parent_full_name] = parent_commit
                    print('getting parent_commit finished')
                    parent_pull_request = Repository.get_pull_requests_commits(parent_full_name)
                    Repository.parent_pulls_requests[parent_full_name] = parent_pull_request
                    print('getting parent_pull_request finished')
                    parent_pull_request_author = Repository.get_all_commits_by_author(parent_full_name)
                    Repository.parent_pulls_requests_authors[parent_full_name] = parent_pull_request_author
                    print('getting parent_pulls_requests_authors finished')

                len_parent_commit = len(parent_commit)
                repo_commit = Repository.get_commits_date(full_name)

            else:

                repo_commit = Repository.get_commits_date(full_name)
                Repository.parent_commits_dict[full_name] = repo_commit
                print('getting parent_commit finished')
                parent_pull_request = Repository.get_pull_requests_commits(full_name)
                Repository.parent_pulls_requests[full_name] = parent_pull_request
                print('getting parent_pull_request finished')
                parent_pull_request_author = Repository.get_all_commits_by_author(full_name)
                Repository.parent_pulls_requests_authors[full_name] = parent_pull_request_author
                print('getting parent_pulls_requests_authors finished')
            if repo.parent:
                Repository.write_to_excel_file(
                    full_name,
                    repo_commit,
                    parent_commit,
                    parent_pull_request,
                    parent_pull_request_author
                )
            print("----------------------------getting repository finished--------------------------------------")
            return dict_total
        except Exception as e:
            print(Fore.RED + str(e))
            print(Back.BLUE + 'error')
            print(Style.RESET_ALL)
Ejemplo n.º 12
0
from github import Github

API_KEY = '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'

githubInstance = Github(base_url="https://api.github.com",
                        login_or_token=API_KEY)

for repo in githubInstance.get_user('angeloevangelista').get_repos():
    print(repo.name)
if get_env_var_name("LABELS") in os.environ:
    if get_env_var("LABELS") == "":
        print("LABELS is empty string, won't filter")
        labels = []
    else:
        labels = get_env_var("LABELS").split(",")
else:
    print("LABELS not specified, won't filter")
    labels = []

slack = WebClient(token=get_env_var("SLACK_TOKEN"))
channel = get_env_var("SLACK_CHANNEL")
slack_webhook = get_env_var("SLACK_WEBHOOK")

try:
    # Subject to GitHub RateLimitExceededException
    github = Github(get_env_var("PAT") or os.getenv("GITHUB_SCRIPT_TOKEN"))
    repo = github.get_repo(get_env_var("REPO_FOR_DATA"))

    transport = AIOHTTPTransport(
        url='https://api.github.com/graphql',
        headers={'Authorization': 'Bearer %s' % get_env_var("PAT")})
    # Create a GraphQL client using the defined transport
    gql_client = Client(transport=transport, fetch_schema_from_transport=True)
    project_dict = resolve_url(gql_client, get_env_var("PROJECT_URL"))

    main(repo, project_dict)
except RateLimitExceededException:
    print("Hit GitHub RateLimitExceededException. Skipping this run.")
Ejemplo n.º 14
0
 def __init__(self, access_token, bot_access_token=None):
     self.github = Github(access_token)
     if bot_access_token:
         self.bot = Github(bot_access_token)
Ejemplo n.º 15
0
# to use this install package
# pip install PyGithub
from github import Github
import requests

# remove the minus sign from the key
# you can add this to your code just don't commit it
# or use an API key to your own repo
g = Github("7aa146eafee094d3a7b1e81aa1d8fcb0eec8b91-0")

#for repo in g.get_user().get_repos():
#    print(repo.name)
    #repo.edit(has_wiki=False)
    # to see all the available attributes and methods
    #print(dir(repo))
repo = g.get_repo("datarepresentationstudent/aPrivateOne")
#print(repo.clone_url)
fileInfo = repo.get_contents("test.txt")
urlOfFile = fileInfo.download_url
#print (urlOfFile)
response = requests.get(urlOfFile)
contentOfFile = response.text
#print (contentOfFile)
newContents = contentOfFile + " more stuff \n"
print (newContents)
gitHubResponse=repo.update_file(fileInfo.path,"updated by prog",newContents,fileInfo.sha)
print (gitHubResponse)
Ejemplo n.º 16
0
def set_up_github_client():
    print("Setting up GitHub client...")
    github_client = Github(GITHUB_TOKEN)
    return github_client
Ejemplo n.º 17
0
def generate_issue_content(
    github_token: str,
    previous_release: str,
    current_release: str,
    excluded_pr_list: str,
    verbose: bool,
    limit_pr_count: Optional[int],
    is_helm_chart: bool,
):
    if excluded_pr_list:
        excluded_prs = [int(pr) for pr in excluded_pr_list.split(",")]
    else:
        excluded_prs = []
    changes = get_changes(verbose, previous_release, current_release,
                          is_helm_chart)
    change_prs = [change.pr for change in changes]
    prs = [
        pr for pr in change_prs if pr is not None and pr not in excluded_prs
    ]

    g = Github(github_token)
    repo = g.get_repo("apache/airflow")
    pull_requests: Dict[int, PullRequestOrIssue] = {}
    linked_issues: Dict[int, List[Issue.Issue]] = defaultdict(lambda: [])
    users: Dict[int, Set[str]] = defaultdict(lambda: set())
    count_prs = len(prs)
    if limit_pr_count:
        count_prs = limit_pr_count
    with Progress(console=console) as progress:
        task = progress.add_task(f"Retrieving {count_prs} PRs ",
                                 total=count_prs)
        for i in range(count_prs):
            pr_number = prs[i]
            progress.console.print(
                f"Retrieving PR#{pr_number}: "
                f"https://github.com/apache/airflow/pull/{pr_number}")

            pr: PullRequestOrIssue
            try:
                pr = repo.get_pull(pr_number)
            except UnknownObjectException:
                # Fallback to issue if PR not found
                try:
                    pr = repo.get_issue(pr_number)  # (same fields as PR)
                except UnknownObjectException:
                    console.print(
                        f"[red]The PR #{pr_number} could not be found[/]")
                    continue

            # Ignore doc-only and skipped PRs
            label_names = [label.name for label in pr.labels]
            if "type:doc-only" in label_names or "changelog:skip" in label_names:
                continue

            pull_requests[pr_number] = pr
            # GitHub does not have linked issues in PR - but we quite rigorously add Fixes/Closes
            # Relate so we can find those from the body
            if pr.body:
                body = pr.body.replace("\n", " ").replace("\r", " ")
                linked_issue_numbers = {
                    int(issue_match.group(1))
                    for issue_match in ISSUE_MATCH_IN_BODY.finditer(body)
                }
                for linked_issue_number in linked_issue_numbers:
                    progress.console.print(
                        f"Retrieving Linked issue PR#{linked_issue_number}: "
                        f"https://github.com/apache/airflow/issue/{linked_issue_number}"
                    )
                    try:
                        linked_issues[pr_number].append(
                            repo.get_issue(linked_issue_number))
                    except UnknownObjectException:
                        progress.console.print(
                            f"Failed to retrieve linked issue #{linked_issue_number}: Unknown Issue"
                        )
            users[pr_number].add(pr.user.login)
            for linked_issue in linked_issues[pr_number]:
                users[pr_number].add(linked_issue.user.login)
            progress.advance(task)
    print_issue_content(current_release, pull_requests, linked_issues, users,
                        is_helm_chart)
import requests
import os
import json
import logging 
from github import Github

owner = os.environ.get("GIT_ORG")
token = os.environ.get("GIT_TOKEN")

with open('github-management/manage-labels/labels.json') as file:
    labels = json.load(file)

g = Github(token)
org = g.get_organization('fuchicorp')
repos = org.get_repos()

for repo in repos:
    for label in labels:

        try:
            remote_label = repo.get_label(label['name'])
            if str(remote_label.name) != label['name'] or str(remote_label.description) != label['description']:
                remote_label.edit(label['name'], label['color'], label['description'])
                logging.warning(f'Updated label {remote_label.name} in {repo.name}')
            else:
                logging.warning(f'the label {remote_label.name} up to date in {repo.name}')
                
        except Exception as e:
            try:
                if 'minimum' in label.keys() and 'maximum' in label.keys():
                    for item in range(label['minimum'], label['maximum'] + 1):
__author__ = "nodiscc"
__copyright__ = "Copyright 2019, nodiscc"
__credits__ = ["https://github.com/kickball/awesome-selfhosted"]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "nodiscc"
__email__ = "*****@*****.**"
__status__ = "Production"

###############################################################################

access_token = os.environ['GITHUB_TOKEN']
""" find all URLs of the form https://github.com/owner/repo """
with open('README.md', 'r') as readme:
    data = readme.read()
    project_urls = re.findall('https://github.com/[A-z]*/[A-z|0-9|\-|_|\.]+',
                              data)

urls = sorted(set(project_urls))
""" Uncomment this to debug the list of matched URLs """
# print(str(urls))
# exit(0)
""" login to github API """
g = Github(access_token)
""" load project metadata, output last commit date and URL """
for url in urls:
    project = re.sub('https://github.com/', '', url)
    repo = g.get_repo(project)
    print(str(repo.pushed_at) + ' https://github.com/' + project)
    bot_label = repo.get_label('bot')
    prs = repo.get_pulls(state='open')

    _merge = "   "
    _successful_builds = set()

    for pr in prs:
        if pr.mergeable:
            _merge =" 👍 "

        print(_merge + " " + str(pr.id) + " " + pr.title)

        for commit in pr.get_commits():
           print("\t"+commit.commit.message)
           print("\t\tTravsi-CI Build ID: " + successful_travis_build_id(commit))

def main():
#    create_bot_tasklist(TRAVIS_REPO_SLUG)
#    handle_open_tasks(TRAVIS_REPO_SLUG)
    check_if_PR_ready_to_merge(TRAVIS_REPO_SLUG)

if __name__ == '__main__':
    if not GITHUB_ACCESS_TOKEN:
        logging.error("No GITHUB_ACCESS_TOKEN")
        exit(-1)

    g = Github(login_or_token=GITHUB_ACCESS_TOKEN)
    logging.info("I am " + g.get_user().name)

    main()
Ejemplo n.º 21
0
from github import Github
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()
g = Github("")
org = g.get_organization('Kenshoo')
repo = org.get_repo('Search')
Ejemplo n.º 22
0
#Accessing information from github

from github import Github

guser = input("Enter username: "******"Enter password: "******"idafan/CS3012SE")
##branches = list(repo.get_branches())
##print(branches)
##
##
##commit = repo.get_commit('master')
##print(commit.commit.author.date)

##for repo in ida.get_user().get_repos():
Ejemplo n.º 23
0
# 4. https://pygithub.readthedocs.io/en/latest/examples/Repository.html#delete-a-file-in-the-repository

from settings import GITHUB_TOKEN
from github import Github

import sys
import os

g = Github(GITHUB_TOKEN)

# https://github.com/steadylearner/posts
repo = g.get_repo("steadylearner/blog")

filepath = sys.argv[1]

print(
    f"Do you really want to delete {colored(filepath, attrs=['bold'])}?(n if you don't want it)"
)
response = input()

if response.startswith("n"):
    print(f"\nIt won't delete {colored(filepath, attrs=['bold'])}.")
else:
    os.remove(filepath)
    print(f"{colored(filepath, attrs=['bold'])} removed")
    contents = repo.get_contents(filepath, ref="master")
    repo.delete_file(contents.path,
                     f"remove {filepath}",
                     contents.sha,
                     branch="master")
    print("It is also removed from the GitHub")
Ejemplo n.º 24
0
def create():
    folderName = str(sys.argv[1])
    os.makedirs(path + str(sys.argv[1]))
    user = Github(username, password).get_user()
    repo = user.create_repo(sys.argv[1])
    print("Succesfully created repository {}".format(sys.argv[1]))
Ejemplo n.º 25
0
 def __init__(self, login):
     self.g = Github()
     self.user = self.g.get_user(login)
try:
    s = Settings()
except ValidationError as e:
    logging.error('error loading Settings\n:%s', e)
    sys.exit(1)

contents = s.github_event_path.read_text()
event = GitHubEvent.parse_raw(contents)

if event.issue.pull_request is None:
    logging.info('action only applies to pull requests, not issues')
    sys.exit(0)

body = event.comment.body.lower()

g = Github(s.input_token.get_secret_value())
repo = g.get_repo(s.github_repository)
pr = repo.get_pull(event.issue.number)
commenter_is_reviewer = event.comment.user.login in s.reviewers
commenter_is_author = event.issue.user.login == event.comment.user.login
reviewers = ', '.join(f'"{r}"' for r in s.reviewers)


def remove_label(label: str):
    labels = pr.get_labels()
    if any(lb.name == label for lb in labels):
        pr.remove_from_labels(label)


def assigned_author() -> Tuple[bool, str]:
    if not commenter_is_reviewer:
Ejemplo n.º 27
0
    return warnings, errors


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    stopwatch = Stopwatch()

    repo_path = REPO_COPY
    temp_path = TEMP_PATH

    pr_info = PRInfo()
    # this check modify repository so copy it to the temp directory
    logging.info("Repo copy path %s", repo_path)

    gh = Github(get_best_robot_token())
    rerun_helper = RerunHelper(gh, pr_info, NAME)
    if rerun_helper.is_already_finished_by_status():
        logging.info(
            "Check is already finished according to github status, exiting")
        sys.exit(0)

    images_path = os.path.join(temp_path, 'changed_images.json')
    docker_image = 'clickhouse/pvs-test'
    if os.path.exists(images_path):
        logging.info("Images file exists")
        with open(images_path, 'r') as images_fd:
            images = json.load(images_fd)
            logging.info("Got images %s", images)
            if 'clickhouse/pvs-test' in images:
                docker_image += ':' + images['clickhouse/pvs-test']
Ejemplo n.º 28
0
def backup(user, password, access_token, organizations, dest):
    """Performs a backup of all the accessible repos in given organizations
    """
    if password is None or user is None:
        logger.error("No valid github credentials provided. Exiting!")
        sys.exit(-1)
    if password is not None:
        github_instance = Github(access_token)
        repositories = []  # list of repository *iterators*
        for organization in organizations:
            logger.info("Github API rate limit: {}".format(
                github_instance.get_rate_limit()))
            github_organization = github_instance.get_organization(
                organization)

            repositories.append(github_organization.get_repos(type='all'))

            # Check that destination directories are set up
            organization_destination_path = os.path.join(dest, organization)
            if not os.path.exists(organization_destination_path):
                os.mkdir(organization_destination_path)

    for repository in chain(*repositories):
        logger.info("Github API rate limit: {}".format(
            github_instance.get_rate_limit()))
        if password is not None and repository.private is True:
            source = repository.clone_url.replace(
                "https://", "https://{}:{}@".format(user, password))
        else:
            source = repository.clone_url

        repository_path = os.path.join(dest, repository.organization.login,
                                       repository.name)
        logger.info("Backing up repository {}".format(repository.name))
        # If the repository is present on destination, update all branches
        if os.path.exists(repository_path):
            logger.info("The repository {} already exists on destination. "
                        "Pulling all branches".format(repository.name))
            with cd(repository_path):
                try:
                    # These stdout and stderr flush out the normal github
                    # output the alternative of using -q doesn't always work
                    check_call(['git', 'stash'], stdout=PIPE, stderr=STDOUT)
                    check_call(['git', 'pull'], stdout=PIPE, stderr=STDOUT)
                # General exception to better catch errors
                except CalledProcessError:
                    logger.error("There was an error fetching the branches "
                                 "from the repository {}, "
                                 "skipping it".format(repository.name))
                    pass
            logger.info("Finished copying repo {}".format(repository.name))
        # Otherwise clone the repository and fetch all branches
        else:
            logger.info("The repository {} isn't cloned at {}, cloning instead"
                        " of updating...".format(repository.name,
                                                 repository_path))
            try:
                check_call(['git', 'clone', source, repository_path],
                           stdout=PIPE,
                           stderr=STDOUT)
                logger.info("Cloning {}".format(repository.name))
            except CalledProcessError as e:
                logger.error("ERROR: Error cloning repository {}, "
                             "skipping it".format(repository.name))
                logger.error(str(e))
                pass
            try:
                with cd(repository_path):
                    check_call(track_all_branches,
                               shell=True,
                               stdout=PIPE,
                               stderr=STDOUT)
                    logger.info("Fetching branches for {}".format(
                        repository.name))
            except CalledProcessError as e:
                logger.error("ERROR: Problem fetching branches for "
                             "repository {}, skipping it".format(
                                 repository.name))
                logger.error(str(e))
                pass
Ejemplo n.º 29
0
def get_github():
    token = conf['token']
    g = Github(token)
    return g
Ejemplo n.º 30
0
Command | Description
-- | --
`@hacs-bot no` | Will close the issue, and not publish a new release.
`@hacs-bot close` | Same as `@hacs-bot no`.
`@hacs-bot yes` | Will create a new release and close the issue.
`@hacs-bot LGTM` | Same as `@hacs-bot yes`.
`@hacs-bot release x.xx.x` | Same as `@hacs-bot yes` but will change the release number to the one specified.

</details>
"""

CHANGE = "- [{line}]({link}) @{author}\n"
NOCHANGE = "_No changes in this release._"

GITHUB = Github(sys.argv[2])


def new_commits(repo, sha):
    """Get new commits in repo."""
    from datetime import datetime

    dateformat = "%a, %d %b %Y %H:%M:%S GMT"
    release_commit = repo.get_commit(sha)
    since = datetime.strptime(release_commit.last_modified, dateformat)
    commits = repo.get_commits(since=since)
    if len(list(commits)) == 1:
        return False
    return reversed(list(commits)[:-1])