本文整理汇总了Python中github3.GitHub类的典型用法代码示例。如果您正苦于以下问题:Python GitHub类的具体用法?Python GitHub怎么用?Python GitHub使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GitHub类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: issues
def issues():
testToIssue = {}
try:
# user = GitHub("<user>",token="<token>")
user = GitHub()
issues = user.issues_on("assaft", "caevo",state="open")
regex = r"\btest\b ([tT]\d+)"
group = 1
for issue in issues:
text = "Issue by " + issue.user.login + ":\n" + issue.title + "\n" + issue.body + "\n\n"
for comment in issue.comments():
text = text + "commit by " + comment.user.login + ":\n" + comment.body + "\n\n"
matches = re.finditer(regex, text)
for match in matches:
test = match.group(group)
#print test
if (test not in testToIssue):
testToIssue[test] = set()
testIssues = testToIssue[test]
testIssues.add(issue.number)
except ForbiddenError as err:
print ('Issues cannot be fetched from GitHub because connection as an anonymous user has failed. Wait for GitHub counter to reset or put your username and password/token in the script. Message from GitHub:\n' + format(err));
except:
sys.exit('Unexpected error fetching issues from GitHub')
return testToIssue;
示例2: run
def run(self):
"""
Main worker.
"""
update_name = None # Store update name, i.e: Eddy v0.9.1
update_version = self.current # Store update version, i.e: 0.9.1
update_url = None # Store update HTML url, i.e: http://github.com/...
try:
LOGGER.info('Connecting to GitHub to retrieve update information (channel: %s)', self.channel.value)
github = GitHub(token='6a417ccfe9a7c526598e77a74cbf1cba6e688f0e')
repository = github.repository('danielepantaleone', 'eddy')
for release in repository.releases():
if self.channel is Channel.Beta or not release.prerelease:
try:
if NormalizedVersion(release.tag_name[1:]) > NormalizedVersion(update_version):
update_name = release.name
update_version = release.tag_name[1:]
update_url = release.html_url
except IrrationalVersionError as e:
LOGGER.warning('Failed to parse version number from TAG: %s', e)
if update_version != self.current:
LOGGER.info('Update available: %s', update_name)
self.sgnUpdateAvailable.emit(update_name, update_url)
else:
LOGGER.info('No update available')
self.sgnNoUpdateAvailable.emit()
except Exception as e:
LOGGER.warning('Failed to retrieve update data: %s', e)
self.sgnNoUpdateDataAvailable.emit()
self.finished.emit()
示例3: main
def main():
username = raw_input("Enter username: ")
password = getpass()
githubObj = GitHub(username, password)
ssh_url_list = []
html_url_list = []
choice = raw_input("Do you want to clone the repositories of your organization? [Y/N] ")
if choice == 'y' or choice == 'Y':
all_repos = githubObj.repositories()
for repo in all_repos:
ssh_url_list.append(repo.ssh_url)
html_url_list.append(repo.html_url)
else:
user_repos = githubObj.repositories_by(username)
for repo in user_repos:
ssh_url_list.append(repo.ssh_url)
html_url_list.append(repo.html_url)
clone_choice = raw_input("Do you want to clone via SSH [Y/N] ")
if clone_choice == 'y' or clone_choice == 'Y':
print "Initiating Cloning via SSH"
for url in ssh_url_list:
os.system("git clone " + url)
else:
print "Initiating Cloning via HTTPS"
for url in html_url_list:
os.system("git clone " + url)
示例4: retrieve_repos_by_keyword
def retrieve_repos_by_keyword(keywords, language, username="", password=""):
gh = None
if username and password:
gh = login(username, password=password)
else:
gh = GitHub()
try:
for keyword in keywords:
for page in range(1, 11):
repos = gh.search_repos(keyword, language=language, start_page=page)
for repo in repos:
r = repo.to_json()
if r["language"] == language:
result = r
try:
user = gh.user(r["owner"]).to_json()
result["owner_email"] = user.get("email", "")
result["owner_blog"] = user.get("blog", "")
result["owner_location"] = user.get("location", "")
result["owner_avatar"] = user.get("avatar_url", "")
except Exception as e:
pass
yield result
except Exception as e:
print e
pass
示例5: _get_latest_release
def _get_latest_release(self):
# Return Release object if new release available, else, return None
if 'alpha' in settings.update_channel:
dev_release = self._get_dev_release()
if dev_release:
return dev_release
else:
dev_release = None
# Check for new beta or release versions
if not dev_release:
owner = OWNER
repo_name = REPO_NAME
# If there is an issue accessing the GitHub API, return None
try:
gh = GitHub()
repo = gh.repository(owner, repo_name)
except GitHubError:
return None
for release in repo.iter_releases():
latest_version = release.name
if Version(current_version) < Version(latest_version):
if (((is_beta(latest_version) or
is_release(latest_version)) and is_beta_channel()) or
(is_release(latest_version) and is_release_channel())):
release_url = (
'https://github.com/%s/%s/archive/%s.tar.gz'
% (owner, repo_name, release.tag_name))
release_notes = release.body
return Release(latest_version, release_url,
release_notes)
else:
return None
示例6: set_pull_request_status
def set_pull_request_status(pr, state, target_url="", description='', user=None,
credfile='gh.cred'):
"""Sets a state for every commit associated ith a pull request.
Parameters
----------
pr : PullRequest or len-3 sequence
A github3 pull request object or a tuple of (owner, repository, number).
state : str
Accepted values are 'pending', 'success', 'error', 'failure'.
target_url : str, optional
URL to link with this status.
description : str, optional
Flavor text.
user : str, None, or NotSpecified, optional
The username to log into github with.
credfile : str, optional
The github credentials file name.
"""
gh = GitHub()
ensure_logged_in(gh, user=user, credfile=credfile)
if isinstance(pr, Sequence):
r = gh.repository(*pr[:2])
pr = gh.pull_request(*pr)
else:
#r = gh.repository(*pr.repository) Broken on github3.py v0.8+
r = gh.repository(*pr.base.repo)
status = r.create_status(pr.head.sha, state=state, target_url=target_url,
description=description)
示例7: fixPullRequestTitle
def fixPullRequestTitle(pullRequestId):
gho = GitHub(githubUser, githubPassword)
oPull = gho.pull_request(githubOwner, githubRepository, str(pullRequestId))
branchName = oPull.head.ref
issueKey = extractIssueKey(branchName)
title = oPull.title
foundIndex = title.find(issueKey)
updateRequired = 0
if foundIndex == 0:
if issueKey == title:
updateRequired = 1
print 'Issue Key ' + issueKey + ' Found in Title but Update Required for ' + title
else:
print 'Issue Key ' + issueKey + ' found in Title for ' + title
return
else:
updateRequired = 1
print 'Issue Key ' + issueKey + ' NOT Found in Title for ' + title
if updateRequired == 1:
jiraIssue = jiraGetIssueInfo(issueKey, config)
title = issueKey + ' ' + jiraIssue.fields.summary
print title
oPull.update(title)
print 'Updated the Title for the Pull Request ' + oPull.html_url
示例8: get_session
def get_session():
"""Fetch and/or load API authorization token for GITHUB."""
ensure_config_dir()
credential_file = os.path.join(CONFIG_DIR, 'github_auth')
if os.path.isfile(credential_file):
with open(credential_file) as fd:
token = fd.readline().strip()
gh = GitHub(token=token)
try: # Test connection before starting
gh.is_starred('github', 'gitignore')
return gh
except GitHubError as exc:
raise_unexpected(exc.code)
sys.stderr.write('Invalid saved credential file.\n')
from getpass import getpass
from github3 import authorize
user = prompt('GITHUB Username')
try:
auth = authorize(
user, getpass('Password for {0}: '.format(user)), 'repo',
'Farcy Code Reviewer',
two_factor_callback=lambda: prompt('Two factor token'))
except GitHubError as exc:
raise_unexpected(exc.code)
raise FarcyException(exc.message)
with open(credential_file, 'w') as fd:
fd.write('{0}\n{1}\n'.format(auth.token, auth.id))
return GitHub(token=auth.token)
示例9: gen
def gen(token):
gh = GitHub(token=token)
stars = gh.starred()
taged_star_tree = Tree()
try:
with open('tag.json', 'r') as tag_file:
repo_tag_dict = json.load(tag_file, object_hook=RepoTagDict)
except FileNotFoundError:
print("invalid tag", file=sys.stderr)
repo_tag_dict = RepoTagDict()
for star in stars:
repo = Repo(star)
if len(repo_tag_dict[repo.full_name]) == 0:
taged_star_tree['Other'].nodes.append(repo)
else:
for tag in repo_tag_dict[repo.full_name]:
taged_star_tree[tag].nodes.append(repo)
with open('tag.json', 'w+') as tag_file:
json.dump(repo_tag_dict, tag_file, indent=' ', sort_keys=True)
print("# TOC")
taged_star_tree.mdtoc(name="Star")
print()
taged_star_tree.mdprint(
name='Star',
node_md=lambda x: '[{}]({}): {}'.format(
str(x), x.url, x.description))
示例10: starred
def starred(username, sort):
"""
"""
gh = GitHub()
stars = gh.starred_by(username)
click.echo(desc)
repo_dict = {}
for s in stars:
language = s.language or 'Others'
description = s.description or ''
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 = ' - [{}](#{})'.format(language, language.lower())
click.echo(data)
click.echo('')
for language in repo_dict:
click.echo('## %s\n' % language)
for repo in repo_dict[language]:
data = '* [{}]({}) - {}'.format(*repo)
click.echo(data)
click.echo('')
示例11: __init__
class GitHubApi:
"""
GitHub API interaction using github3
"""
def __init__(self, repo_owner, repo_name, token):
self.repo_owner = repo_owner
self.repo_name = repo_name
self.gh = GitHub(token=token)
def get_issues(self, label=None):
"""Returns all issues (matching label)"""
return self.gh.iter_repo_issues(self.repo_owner, self.repo_name, labels=label)
def get_issue(self, issue_id):
"""Returns issue"""
return self.gh.issue(self.repo_owner, self.repo_name, issue_id)
def get_matching_pull_requests(self, label=None):
"""
Returns all matching issues
Pull requests are treated as issues
"""
pull_request_list = []
for issue in self.get_issues(label):
# Get Pull Request
pull_request_list.append(self.pull_request_information(issue.number))
return pull_request_list
def get_pull_request_status(self, label=None):
"""Returns string containing status of pull requests"""
pull_requests = self.get_matching_pull_requests(label)
pull_requests_information = "Pull Requests - %s\n\n" % label
for pr in pull_requests:
pull_requests_information += "Title: %s\nBranch: %s\nLink: %s\nMergeable: %s\n\n"\
% (pr.title, pr.head.ref, pr.html_url, pr.mergeable)
return pull_requests_information
def pull_request_information(self, pull_request_id):
"""Returns specified pull request"""
pull_request = self.gh.pull_request(self.repo_owner, self.repo_name, pull_request_id)
return pull_request
def assign_new_label_to_issue(self, branch, label, who):
"""Update issue label"""
# Find issue
issue = self.filter_on_branch(self.get_matching_pull_requests(), branch)
# Remove all existing labels
issue.remove_all_labels()
# Add label 'release'
issue.add_labels(label)
# Add comment for tracking
issue.create_comment("%s assigned label '%s' via hipchat" % (who, label))
def filter_on_branch(self, pull_requests, branch):
for pull_request in pull_requests:
if pull_request.head.ref == branch:
# Get issue
return self.get_issue(pull_request.number)
示例12: __init__
def __init__(self, repo_user = 'OSMBrasil', repo_name = 'semanario'):
"""
@params
repo_user - name of organization or user
repo_name - repository name
"""
github = GitHub()
self.repo = github.repository(repo_user, repo_name)
示例13: 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)
示例14: one_repo_only
def one_repo_only(owner, reponame, gh_token=''):
"""
Go back and see why this or that denied request. Provide a valid token.
"""
gh = GitHub(token=gh_token)
user = gh.me()
body = ISSUE_BODY.format(user)
repo = gh.repository(owner, reponame)
i = repo.create_issue(ISSUE_TITLE, body=body)
print(i)
示例15: GitHubDB
class GitHubDB(object):
def __init__(self, ghtoken):
# Get handle to Github API
if ghtoken is not None and ghtoken != '':
self.gh = login(token=ghtoken)
else:
log.warning('Using unauthenticated access to Github API. This will result in severe rate limiting.')
self.gh = GitHub()
def waitForRateLimit(self, resourceType):
"""resourceType can be 'search' or 'core'."""
try:
rateLimitInfo = self.gh.rate_limit()['resources']
while rateLimitInfo[resourceType]['remaining'] < (1 if resourceType == 'search' else 12):
waitTime = max(1, rateLimitInfo[resourceType]['reset'] - time.time())
log.warning('Waiting %s seconds for Github rate limit...', waitTime)
time.sleep(waitTime)
rateLimitInfo = self.gh.rate_limit()['resources']
except ConnectionError as e:
log.error("Connection error while querying GitHub rate limit. Retrying...")
self.waitForRateLimit(resourceType)
def refreshGithubUser(self, ghUserObject):
self.waitForRateLimit('core')
return ghUserObject.refresh(True)
def getGithubUserForLogin(self, login, session):
"""Uses the Github API to find the user for the given username. Returns NullObject if the user was not found for any reason."""
# Try to use cached result to avoid hitting rate limit
cachedUser = session.query(GitHubUserCache).filter(GitHubUserCache.login == login).first()
if cachedUser is not None:
return cachedUser if not cachedUser.fake else NullObject()
log.debug('Querying GutHub API for login %s', login)
try:
self.waitForRateLimit('core')
potentialUser = self.gh.user(login)
if potentialUser is None:
# store login as fake
session.add(GitHubUserCache(login=login, fake=True))
return NullObject()
actualUser = self.refreshGithubUser(potentialUser)
if isinstance(potentialUser, NullObject):
# store login as fake
session.add(GitHubUserCache(login=login, fake=True))
else:
# cache user
session.add(GitHubUserCache(login=login, name=actualUser.name, email=actualUser.email, company=actualUser.company, location=actualUser.location))
return actualUser
except ConnectionError:
log.error("github query failed when attempting to verify username %s", login)
return NullObject()
def searchGithubUsers(self, query):
self.waitForRateLimit('search')
return self.gh.search_users(query)