def _get_entry(self, languages, known_languages):
entry = []
for language in known_languages:
if language in languages:
entry += [languages[language]]
else:
entry += [0]
sum_entry = sum(entry)
if sum_entry != 0:
entry = [x / sum_entry for x in entry]
return entry
##
# \brief Classifies the reoisitory based on the learned <em>Decision Tree</em>.
#
# \param data GitHub repository as github.Github object.
# \return Dictionary {CLASS: PROBABILITY}, where CLASS is a string containing the class label and
# PROBABILITY is a float in [0.0, 1.0] containing the probability that the repository belongs to the class.
python类Github()的实例源码
def setUp(self):
# setup config
configserver._CONGIF['maximum_cache_age'] = 366000 # About 1000 years
configserver._CONGIF['cache_path'] = './tests/cache'
configserver._CONGIF['model_path'] = './tests/models'
self.classifier = classifier.get_all_classifiers()
self.github_list = [github.Github('Top-Ranger', 'kana-keyboard'),
github.Github('Top-Ranger', 'CHI2016-SUR-datasets'),
github.Github('Top-Ranger', 'SPtP_learningdb'),
github.Github('Top-Ranger', 'SUR213'),
github.Github('Top-Ranger', 'bakery'),
github.Github('Top-Ranger', 'fooling_dnn'),
github.Github('Top-Ranger', 'harbour-hiragana'),
github.Github('Top-Ranger', 'harbour-katakana'),
github.Github('Top-Ranger', 'harbour-reversi'),
github.Github('Top-Ranger', 'qnn'),
github.Github('Top-Ranger', 'SPtP')]
def __init__(self, *, api_url=_DEFAULT_BASE_URL, clone_protocol="ssh", **kwargs):
super().__init__(**kwargs)
self._clone_protocol = self.CloneProtocol(clone_protocol)
self._gh = github.Github(
login_or_token=os.environ.get("GITHUB_TOKEN"),
base_url=api_url
)
def create_pr_to_master(target_branch):
"""create a github pr from target_branch to master"""
git = Github(os.environ.get('GITHUB_ACCESS_TOKEN'))
repo = git.get_user().get_repo('mattermost-openshift')
print(repo.pulls_url)
repo.create_pull('automated update',
'This PR is generated as part of an automated update triggered by a new Mattermost release.', 'master', target_branch)
def get_repo(token, name, org):
gh = Github(token)
if org:
return gh.get_organization(org).get_repo(name=name)
return gh.get_user().get_repo(name=name)
def handle(self):
client = Github(self.username, self.password)
today_commit_events = get_today_commit_events(client.get_user(self.username))
if len(today_commit_events) == 0:
return False
else:
return True
def get_github():
with open(os.path.join(os.path.dirname(__file__), "..", "ghtoken.txt")) as f:
ghtoken = f.read().strip()
return github.Github(ghtoken)
def get_repository(name, username=None, password=None, auth_required=False):
username = username or os.getenv('GITHUB_USERNAME')
password = password or os.getenv('GITHUB_PASSWORD')
if auth_required and not (username and password):
raise Exit('Mandatory GitHub username/password not given.')
return Github(username, password).get_repo(name)
def main():
parser = ArgumentParser(description="Retrieve Github activity")
parser.add_argument('month', type=int, help='Month for activity log')
args = parser.parse_args()
g = Github(GITHUB_USERNAME, GITHUB_PASS)
usr = g.get_user(GITHUB_USERNAME)
year = datetime.now().year
this = (year, int(args.month))
tpl = "{0} - {1}: {2}"
for event in usr.get_public_events():
# go back in history until the start date is reached
if event.type != u"PushEvent":
continue
if month(event.created_at.date()) > this:
continue
# if month(event.created_at.date()) < this:
# break
repo_url = event._repo.value.html_url
if not is_work_repo(repo_url):
continue
repo = repo_url.split('/')[-1]
commits = event.payload['commits']
for commit in commits:
if GITHUB_AUTHOR not in commit['author']['name'].lower():
continue
print(tpl.format(event.created_at.date(),
repo,
commit['message']))
def process(input):
gh_username = setup.get_gh_username()
gh_password = setup.decrypt_password()
gh = github.Github(gh_username, gh_password)
click.echo(chalk.blue('you are in git module'))
click.echo('input = %s' % input)
USER_CONFIG_FILE_PATH = get_config_file_paths()['USER_CONFIG_FILE_PATH']
USER_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(USER_CONFIG_FILE_PATH)
repo = porcelain.init(USER_CONFIG_FOLDER_PATH)
porcelain.add(repo)
porcelain.commit(repo, "A sample commit")
porcelain.remote_add(repo, ".yoda", "https://github.com/manparvesh/.yoda")
porcelain.push(repo, "https://github.com/manparvesh/.yoda")
def get_repos(key, org, repo, url):
if url:
g = Github(key, base_url=url)
else:
g = Github(key)
if org:
g_org = g.get_organization(login=org)
else:
g_org = g.get_user()
if repo:
repos = [g_org.get_repo(repo)]
else:
repos = g_org.get_repos()
return repos
def _get_current_repo(github, repo, remote='origin'):
"""
Gets the github repo associated with the
provided repo
:param Github github:
:param Repo repo:
:param unicode remote:
:return: The github repository assocated with
the provided repo
:rtype: github.Repository.Repository
"""
owner, repo = _get_org_and_name_from_remote(repo.remotes[remote])
return github.get_repo('{0}/{1}'.format(owner, repo))
def _instantiate_github(username):
"""
Gets a github object that has been authenticated.
If authentication fails it asks the user for their
password agains
:param unicode username:
:rtype: Github
"""
password = get_github_password(username)
count = 0
while True:
count += 1
github = Github(login_or_token=username, password=password)
try:
auth = github.get_user().create_authorization(
scopes=['repo'],
note='github-reviewboard-sync {0}'.format(str(uuid4())))
return github, auth
except BadCredentialsException as exc:
_LOG.error('The password was not valid for "{0}"'.format(username))
if count == 3:
raise AuthenticationException('Failed to authenticate three times. '
'Is "{0}" the correct username?'.format(username))
password = get_github_password(username, refresh=True)
except TwoFactorException as exc:
user = github.get_user()
onetime_password =input('Github 2-Factor code: ')
authorization = user.create_authorization(
scopes=['repo'],
note='github-reviewboard-sync {0}'.format(str(uuid4())),
onetime_password=onetime_password)
return Github(authorization.token), authorization
def main():
user = os.environ.get('GH_USER') or USER
logging.info("tracking stars for user {}".format(user))
logging.info("If this is not your username, change it in the python file")
user = Github(os.environ.get('GH_TOKEN') or TOKEN or get_token()).get_user(USER)
for repo in user.get_starred():
repo_ = {
'name': repo.full_name,
'description': repo.description,
'releases': list(),
}
logging.info("getting {}".format(repo.full_name))
for release in repo.get_releases():
release_date = parse_date(release.raw_data['published_at'])
if NOW - release_date < dt.timedelta(days=DAYS):
repo_['releases'].append(release.raw_data)
else:
break # TODO XXX we assume, that those releases are ordered
for tag in repo.get_tags():
sha = tag.raw_data['commit']['sha']
commit = repo.get_commit(sha)
tag_date = parse_date(commit.raw_data['commit']['author']['date'])
if (NOW - tag_date < dt.timedelta(days=DAYS)):
if tag.name not in [r['name'] for r in repo_['releases']]:
tag.raw_data['tag_name'] = ''
tag.raw_data['published_at'] = commit.raw_data['commit']['author']['date']
repo_['releases'].append(tag.raw_data)
else:
break
if repo_['releases']:
print(format_repo(repo_))
def parse_args(args):
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'repo',
help='Github repo to export, in format "owner/repo_name".',
type=str,
action='store',
# TODO - validate this is in correct format.
)
parser.add_argument(
'outpath',
help='Path to write exported issues.',
type=str,
action='store',
)
parser.add_argument(
'-l',
'--login',
help='Prompt to login as this Github user. If provided, this takes '
'precedence over any token found in the environment. If not '
'provided and no token is found, you will be prompted to login as '
'the repository owner.',
type=str,
action='store',
dest='login_user',
)
parser.add_argument(
'-t',
'--token',
help='Automatically login with this Github API token. If --login is '
'provided, this is ignored.',
type=str,
action='store',
dest='token',
)
return parser.parse_args(args)
def export_issues_to_markdown_file(repo, outpath):
formatted_issues = []
for issue in repo.get_issues(state='all'):
# The Github API includes pull requests as "issues". Skip
# closed PRs, as they will add a lot of noise to the export.
try:
if issue.pull_request and issue.state.lower() == 'closed':
continue
except:
traceback.print_exc()
print("Caught exception checking whether issue is PR, skipping")
continue
# Try multiple times to process the issue and append to main issue list
try:
formatted_issue = process_issue_to_markdown(issue)
except:
traceback.print_exc()
print("Couldn't process issue due to exceptions, skipping")
continue
else:
formatted_issues.append(formatted_issue)
full_markdown_export = templates_markdown.BASE.format(
repo_name=repo.full_name,
repo_url=repo.html_url,
issues="\n".join(formatted_issues),
date=datetime.datetime.now().strftime('%Y.%m.%d at %H:%M:%S')
)
print("Exported {} issues".format(len(formatted_issues)))
print("Writing to file: {}".format(outpath))
with open(outpath, 'wb') as out:
out.write(full_markdown_export.encode('utf-8'))
return None
def github_login(login_user=None, token=None, fallback_user=None):
assert login_user or token or fallback_user
per_page = 100
if login_user:
password = getpass.getpass("Github password for {} :".format(login_user))
return Github(login_or_token=login_user, password=password, per_page=per_page)
if token:
return Github(login_or_token=token, per_page=per_page)
password = getpass.getpass("Github password for {} :".format(fallback_user))
return Github(login_or_token=fallback_user, password=password, per_page=per_page)
def print_rate_limit(gh):
limit = gh.get_rate_limit()
print("Github API rate limit: {}".format(limit.rate.raw_data))
def github_from_request(request):
provider = request.user.social_auth.get(provider='github-org')
return github.Github(provider.extra_data['access_token'])
github_to_aws_migration.py 文件源码
项目:analytics-platform-ops
作者: ministryofjustice
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def main():
github = Github(GITHUB_TOKEN)
org = github.get_organization(GITHUB_ORG)
for member in org.get_members():
create_user_role(member.login)
for team in org.get_teams():
create_team_bucket(team.slug)
for member in team.get_members():
attach_bucket_policy(team.slug, member.login)