def _get_files_tree_api(repo_api, sha):
"""Get repo file paths using GitHub Tree API.
"""
files = []
# https://github.com/sigmavirus24/github3.py/issues/656
tree = repo_api.tree('%s?recursive=1' % sha).to_json()
if tree['truncated']:
return None
for item in tree['tree']:
if item['type'] == 'blob':
files.append(item['path'])
return files
python类GitHub()的实例源码
def _get_files_contents_api(repo_api, sha, contents=None):
"""Get repo file paths using GitHub Contents API.
"""
files = []
if not contents:
contents = repo_api.contents('', sha)
for key in sorted(contents):
item = contents[key]
if item.type == 'file':
files.append(item.path)
elif item.type == 'dir':
dir_contents = repo_api.contents(item.path, sha)
files.extend(
_get_files_contents_api(repo_api, sha, dir_contents))
return files
def __init__(self):
if settings.GITHUB_TOKEN:
self.github = login(token=settings.GITHUB_TOKEN)
else:
self.github = GitHub()
def login():
token = ensure_token()
gh_api = github3.GitHub()
gh_api.login(token=token)
ui.info_2("Successfully logged in on GitHub with login", gh_api.user().login)
return gh_api
def github_mock():
github_mock = mock.create_autospec(github3.GitHub, instance=True)
mock_session = mock.Mock()
github_mock._session = mock_session
return github_mock
def check_for_update(self):
def find_update():
logging.debug("Checking remote for new updates.")
try:
gh = GitHub()
repo = gh.repository("phac-nml", "irida-miseq-uploader")
# get the latest tag from github
return next(repo.iter_tags(number=1))
except:
logging.warn("Couldn't reach github to check for new version.")
raise
def handle_update(result):
latest_tag = result.get()
logging.debug("Found latest version: [{}]".format(latest_tag))
release_url = self.url + "/releases/latest"
if LooseVersion(self.__app_version__) < LooseVersion(latest_tag.name):
logging.info("Newer version found.")
dialog = NewVersionMessageDialog(
parent=None,
id=wx.ID_ANY,
message=("A new version of the IRIDA MiSeq "
"Uploader tool is available. You can"
" download the latest version from "),
title="IRIDA MiSeq Uploader update available",
download_url=release_url,
style=wx.CAPTION|wx.CLOSE_BOX|wx.STAY_ON_TOP)
dialog.ShowModal()
dialog.Destroy()
else:
logging.debug("No new versions found.")
dr.startWorker(handle_update, find_update)
def __init__(self, *args, **kwarg):
self.gh = github3.GitHub()
super(GithubService, self).__init__(*args, **kwarg)
def __init__(self, repo_url=None):
self.repo_url = repo_url
self.user_name = None
self.repo_name = None
self.github = None # GitHub Object from github3.py
self.repo = None
self.api_token = config.github_api_token
def __init__(self, _ask_credentials=None, _ask_2fa=None):
self.last_error = None
self._ask_credentials = _ask_credentials
self._ask_2fa = _ask_2fa
self.gh = GitHub(token=self._get_authorization_token())
self.user = self.gh.user()
def __init__(self, login='', password='', token=''):
super(GitHub, self).__init__({})
if token:
self.login(login, token=token)
elif login and password:
self.login(login, password)
def _repr(self):
if self._session.auth:
return '<GitHub [{0[0]}]>'.format(self._session.auth)
return '<GitHub at 0x{0:x}>'.format(id(self))
def authorize(self, login, password, scopes=None, note='', note_url='',
client_id='', client_secret=''):
"""Obtain an authorization token from the GitHub API for the GitHub
API.
:param str login: (required)
:param str password: (required)
:param list scopes: (optional), areas you want this token to apply to,
i.e., 'gist', 'user'
:param str note: (optional), note about the authorization
:param str note_url: (optional), url for the application
:param str client_id: (optional), 20 character OAuth client key for
which to create a token
:param str client_secret: (optional), 40 character OAuth client secret
for which to create the token
:returns: :class:`Authorization <Authorization>`
"""
json = None
# TODO: Break this behaviour in 1.0 (Don't rely on self._session.auth)
auth = None
if self._session.auth:
auth = self._session.auth
elif login and password:
auth = (login, password)
if auth:
url = self._build_url('authorizations')
data = {'note': note, 'note_url': note_url,
'client_id': client_id, 'client_secret': client_secret}
if scopes:
data['scopes'] = scopes
with self._session.temporary_basic_auth(*auth):
json = self._json(self._post(url, data=data), 201)
return Authorization(json, self) if json else None
def emojis(self):
"""Retrieves a dictionary of all of the emojis that GitHub supports.
:returns: dictionary where the key is what would be in between the
colons and the value is the URL to the image, e.g., ::
{
'+1': 'https://github.global.ssl.fastly.net/images/...',
# ...
}
"""
url = self._build_url('emojis')
return self._json(self._get(url), 200)
def iter_starred(self, login=None, sort=None, direction=None, number=-1,
etag=None):
"""Iterate over repositories starred by ``login`` or the authenticated
user.
.. versionchanged:: 0.5
Added sort and direction parameters (optional) as per the change in
GitHub's API.
:param str login: (optional), name of user whose stars you want to see
:param str sort: (optional), either 'created' (when the star was
created) or 'updated' (when the repository was last pushed to)
:param str direction: (optional), either 'asc' or 'desc'. Default:
'desc'
:param int number: (optional), number of repositories to return.
Default: -1 returns all repositories
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Repository <github3.repos.Repository>`
"""
if login:
return self.user(login).iter_starred(sort, direction)
params = {'sort': sort, 'direction': direction}
self._remove_none(params)
url = self._build_url('user', 'starred')
return self._iter(int(number), url, Repository, params, etag)
def set_client_id(self, id, secret):
"""Allows the developer to set their client_id and client_secret for
their OAuth application.
:param str id: 20-character hexidecimal client_id provided by GitHub
:param str secret: 40-character hexidecimal client_secret provided by
GitHub
"""
self._session.params = {'client_id': id, 'client_secret': secret}
def _repr(self):
return '<GitHub Enterprise [0.url]>'.format(self)
def _repr(self):
return '<GitHub Status>'