# Path: ghtools/cli.py
# def catch_api_errors():
# def fail(message, exit_code=1):
# def get_client(nickname):
# def parse_identifier(identifier, require_repo=False):
# 
# Path: ghtools/api.py
# def envkey(nickname, key):
#     return 'GITHUB_{0}_{1}'.format(nickname.upper(), key.upper())
# 
# class GithubAPIClient(object):
#     def __init__(self, root=None, nickname=None):
#         self._session = requests.Session()
#         self._session.headers['content-type'] = 'application/json'
# 
#         if nickname is not None:
#             self.nickname = nickname
#         else:
#             self.nickname = DEFAULT_GITHUB
#         self.token = self._env('oauth_token')
# 
#         # Try to ascertain GitHub API root
#         if root is not None:
#             self.root = root
#         elif self._env('api_root') is not None:
#             self.root = self._env('api_root')
#         else:
#             try:
#                 self.root = KNOWN_GITHUBS[self.nickname]
#             except KeyError:
#                 msg = "No known API root for nickname '{0}'. Perhaps you need to set ${1}?".format(
#                     self.nickname,
#                     envkey(self.nickname, 'api_root')
#                 )
#                 raise GithubError(msg)
# 
#         # Use specified SSL CA Bundle if provided
#         ca_bundle = self._env('ca_bundle')
#         if ca_bundle is not None:
#             self._session.verify = ca_bundle
# 
#         log.debug("Created %s", self)
# 
#     def _env(self, key, default=None):
#         return env.get(
#             envkey(self.nickname, key),
#             default
#         )
# 
#     def _req(self, method, url, _raise=True, *args, **kwargs):
#         if "data" in kwargs and (isinstance(kwargs['data'], int) or isinstance(kwargs['data'], dict)):
#             kwargs['data'] = json.dumps(kwargs['data'])
# 
#         if env.get("GHTOOLS_DEBUG", False):
#             print(method, url, args, kwargs)
#         res = self._session.request(method, url, *args, **kwargs)
#         if env.get("GHTOOLS_DEBUG", False):
#             print(res, res.text, res.headers)
#         if _raise:
#             custom_raise_for_status(res)
#         return res
# 
#     def _url(self, path):
#         return self.root + path
# 
#     def login(self, username, password, scopes=None, comment=None):
#         if scopes is None:
#             scopes = []
# 
#         ver = __version__
#         now = datetime.utcnow().replace(microsecond=0)
# 
#         comment_str = ''
#         if comment is not None:
#             comment_str = ', "{0}"'.format(comment)
# 
#         note = 'ghtools {0} (created {1}{2})'.format(ver, now.isoformat(), comment_str)
# 
#         data = {
#             'note': note,
#             'scopes': scopes,
#         }
# 
#         res = self.post(
#             '/authorizations',
#             auth=(username, password),
#             data=json.dumps(data)
#         )
# 
#         self.token = res.json()['token']
# 
#     @property
#     def token(self):
#         return self._token
# 
#     @token.setter
#     def token(self, tok):
#         self._token = tok
#         if tok is not None:
#             self._session.headers['Authorization'] = 'token {0}'.format(self._token)
# 
#     @property
#     def logged_in(self):
#         return self.token is not None
# 
#     def request(self, method, url, *args, **kwargs):
#         return self._req(method, self._url(url), *args, **kwargs)
# 
#     def delete(self, url, *args, **kwargs):
#         return self._req('delete', self._url(url), *args, **kwargs)
# 
#     def get(self, url, *args, **kwargs):
#         return self._req('get', self._url(url), *args, **kwargs)
# 
#     def patch(self, url, *args, **kwargs):
#         return self._req('patch', self._url(url), *args, **kwargs)
# 
#     def post(self, url, *args, **kwargs):
#         return self._req('post', self._url(url), *args, **kwargs)
# 
#     def put(self, url, *args, **kwargs):
#         return self._req('put', self._url(url), *args, **kwargs)
# 
#     def paged_get(self, url, *args, **kwargs):
#         for res in paged(self._session, 'get', self._url(url)):
#             for item in res.json():
#                 yield item
# 
#     def __str__(self):
#         return '<GithubAPIClient {0}={1}>'.format(self.nickname, self.root)


from getpass import getpass, _raw_input
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import envkey, GithubAPIClient
import logging
import sys
def login_if_needed(gh, scopes, comment):
    if gh.logged_in:
        log.info("Already logged in")
        return

    print("Please log into GitHub ({0})".format(gh.nickname or "public"),
          file=sys.stderr)
    username = _raw_input("Username: ")
    password = getpass("Password: ")

    gh.login(username, password, scopes=scopes, comment=comment)


@arg('-s', '--scope',
     default=None,
     action='append',
     help='GitHub auth scopes to request')
@arg('-c', '--comment',
     help='Comment to attach to the auth token request')
@arg('github',
     nargs='?',
     help='GitHub instance nickname (e.g "enterprise")')
def login(args):
    """
    Log into a GitHub instance, and print the resulting OAuth token.
    """
    with cli.catch_api_errors():
        client = GithubAPIClient(nickname=args.github)
        login_if_needed(client, args.scope, comment=args.comment)


# Path: ghtools/cli.py
# def catch_api_errors():
# def fail(message, exit_code=1):
# def get_client(nickname):
# def parse_identifier(identifier, require_repo=False):
# 
# Path: ghtools/api.py
# def envkey(nickname, key):
#     return 'GITHUB_{0}_{1}'.format(nickname.upper(), key.upper())
# 
# class GithubAPIClient(object):
#     def __init__(self, root=None, nickname=None):
#         self._session = requests.Session()
#         self._session.headers['content-type'] = 'application/json'
# 
#         if nickname is not None:
#             self.nickname = nickname
#         else:
#             self.nickname = DEFAULT_GITHUB
#         self.token = self._env('oauth_token')
# 
#         # Try to ascertain GitHub API root
#         if root is not None:
#             self.root = root
#         elif self._env('api_root') is not None:
#             self.root = self._env('api_root')
#         else:
#             try:
#                 self.root = KNOWN_GITHUBS[self.nickname]
#             except KeyError:
#                 msg = "No known API root for nickname '{0}'. Perhaps you need to set ${1}?".format(
#                     self.nickname,
#                     envkey(self.nickname, 'api_root')
#                 )
#                 raise GithubError(msg)
# 
#         # Use specified SSL CA Bundle if provided
#         ca_bundle = self._env('ca_bundle')
#         if ca_bundle is not None:
#             self._session.verify = ca_bundle
# 
#         log.debug("Created %s", self)
# 
#     def _env(self, key, default=None):
#         return env.get(
#             envkey(self.nickname, key),
#             default
#         )
# 
#     def _req(self, method, url, _raise=True, *args, **kwargs):
#         if "data" in kwargs and (isinstance(kwargs['data'], int) or isinstance(kwargs['data'], dict)):
#             kwargs['data'] = json.dumps(kwargs['data'])
# 
#         if env.get("GHTOOLS_DEBUG", False):
#             print(method, url, args, kwargs)
#         res = self._session.request(method, url, *args, **kwargs)
#         if env.get("GHTOOLS_DEBUG", False):
#             print(res, res.text, res.headers)
#         if _raise:
#             custom_raise_for_status(res)
#         return res
# 
#     def _url(self, path):
#         return self.root + path
# 
#     def login(self, username, password, scopes=None, comment=None):
#         if scopes is None:
#             scopes = []
# 
#         ver = __version__
#         now = datetime.utcnow().replace(microsecond=0)
# 
#         comment_str = ''
#         if comment is not None:
#             comment_str = ', "{0}"'.format(comment)
# 
#         note = 'ghtools {0} (created {1}{2})'.format(ver, now.isoformat(), comment_str)
# 
#         data = {
#             'note': note,
#             'scopes': scopes,
#         }
# 
#         res = self.post(
#             '/authorizations',
#             auth=(username, password),
#             data=json.dumps(data)
#         )
# 
#         self.token = res.json()['token']
# 
#     @property
#     def token(self):
#         return self._token
# 
#     @token.setter
#     def token(self, tok):
#         self._token = tok
#         if tok is not None:
#             self._session.headers['Authorization'] = 'token {0}'.format(self._token)
# 
#     @property
#     def logged_in(self):
#         return self.token is not None
# 
#     def request(self, method, url, *args, **kwargs):
#         return self._req(method, self._url(url), *args, **kwargs)
# 
#     def delete(self, url, *args, **kwargs):
#         return self._req('delete', self._url(url), *args, **kwargs)
# 
#     def get(self, url, *args, **kwargs):
#         return self._req('get', self._url(url), *args, **kwargs)
# 
#     def patch(self, url, *args, **kwargs):
#         return self._req('patch', self._url(url), *args, **kwargs)
# 
#     def post(self, url, *args, **kwargs):
#         return self._req('post', self._url(url), *args, **kwargs)
# 
#     def put(self, url, *args, **kwargs):
#         return self._req('put', self._url(url), *args, **kwargs)
# 
#     def paged_get(self, url, *args, **kwargs):
#         for res in paged(self._session, 'get', self._url(url)):
#             for item in res.json():
#                 yield item
# 
#     def __str__(self):
#         return '<GithubAPIClient {0}={1}>'.format(self.nickname, self.root)


# Path: ghtools/command/login.py
from getpass import getpass, _raw_input
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import envkey, GithubAPIClient
import logging
import sys

def login_if_needed(gh, scopes, comment):
    if gh.logged_in:
        log.info("Already logged in")
        return

    print("Please log into GitHub ({0})".format(gh.nickname or "public"),
          file=sys.stderr)
    username = _raw_input("Username: ")
    password = getpass("Password: ")

    gh.login(username, password, scopes=scopes, comment=comment)


@arg('-s', '--scope',
     default=None,
     action='append',
     help='GitHub auth scopes to request')
@arg('-c', '--comment',
     help='Comment to attach to the auth token request')
@arg('github',
     nargs='?',
     help='GitHub instance nickname (e.g "enterprise")')
def login(args):
    """
    Log into a GitHub instance, and print the resulting OAuth token.
    """
    with cli.catch_api_errors():
        client = GithubAPIClient(nickname=args.github)
        login_if_needed(client, args.scope, comment=args.comment)


        oauth_token_key = envkey(client.nickname, 'oauth_token')