Exemple #1
0
def _get_gist(id):
  api.getCredentials()
  log.debug ("Internal: _get_gist: " + id)

  url = "/gists/" + id
  gist = api.get(url)
  return gist
Exemple #2
0
def isFile (obj):
  log.debug ("isFile: " + str(obj))
  obj_str = str(obj)
  if ' ' in obj_str:
    return False
  elif os.path.isfile(obj_str) and not os.path.islink(obj_str):
    return True
  return False
Exemple #3
0
def isFileOrDir (obj):
  log.debug ("isFileOrDir: " + str(obj))
  obj_str = str(obj)
  if ' ' in obj_str:
    return False
  elif os.path.isfile(obj_str) or os.path.isdir(obj_str):
    return True
  return False
Exemple #4
0
def readFile (filename):
  log.debug ("readFile: " + str(filename))
  content = None
  if filename != None and os.path.exists(filename):
    try:
      file = open(filename)
      content = file.read()
      file.close()
    except Exception as e:
      log.error ("Unable to read file '{0}'.".format(filename))
  return content
Exemple #5
0
def open(id):
  log.debug("open Gist with ID: {0} ".format(id))

  if id[0] in _cmds['#']:
    api.getCredentials()
    id = _get_id_for_index(id)

  if id:
    gist = _get_gist(id)
    html_url = gist['html_url']
    log.debug("open Gist html_url : {0}".format(html_url))
    call(["open", html_url])
Exemple #6
0
def parseBool (obj):
  log.debug ("parseBool: " + str(obj))
  obj_str = str(obj).strip().lower()
  if obj == True or obj == 1:
    return True
  if obj == False or obj == 0:
    return False
  if obj_str in ("true", "yes", "1", "y"):
    return True
  if obj_str in ("false", "no", "0", "n"):
    return False
  return None
Exemple #7
0
def get (id, path, fileName=''):
  log.debug ("Downloading Gist with Id '{0}' (fileName: {1}) to '{2}'.".format (id, fileName, path))

  if id[0] in _cmds['#']:
    id = _get_id_for_index(id)

  if id:
    gist = _get_gist(id)
    target = os.path.join(path,id)

    print(('Gist \'{0}\' has {1} file(s)'.format(id, len(gist['files']))))
    for file in gist['files']:
      print(('  ' + file))
    dmsg = 'file(s)' if fileName == '' else "'" + fileName + "'"
    confirm = util.readConsole(prompt="Download {0} to (1) '{1}/' or (2) '{2}/'?: ".format(dmsg, path, target))
    if confirm in ('1', '2'):
      filesDownloaded = 0
      try:
        if not os.path.isdir(path):
          os.makedirs(path)
        if confirm == '1':
          target = path
        else:
          os.makedirs(target)
        for (file, data) in list(gist['files'].items()):
          downLoadFile = False
          if fileName != '':
            if fileName.strip().lower() == file.strip().lower():
              downLoadFile = True
          else:
            downLoadFile = True
          if downLoadFile == True:
            content = data['content']
            filepath = os.path.join(target,file)
            file = open( filepath , 'w')
            file.write(content)
            file.close()
            filesDownloaded += 1
            log.debug( 'Saved file:' + filepath )
        print(('{0} File(s) downloaded.'.format(filesDownloaded)))
      except Exception as e:
        print("Insufficient privilages to write to %s." % target)
        print("Error message: " + str(e))
    else:
      print('Ok. I won\'t download the Gist.')
Exemple #8
0
def _checkStatus(request):
    code = request.status_code

    log.debug('Github API Response Code: %s' % str(code))
    log.debug(request.headers)

    if code == 200 or code == 201 or code == 204:
        pass
    elif code == 404 or code == 403:
        print('Please check your user name and/or password.')
        sys.exit(0)
    elif code == 400:
        print('Bad Request')
        sys.exit(0)
    elif code == 422:
        print('Unprocessable Entity')
        sys.exit(0)
    else:
        print('Uknown Error: ' + str(code))
        sys.exit(0)
Exemple #9
0
def view (id, fileName=''):
  log.debug("Viewing Gist with ID: {0} and fileName: '{1}'".format(id,fileName))

  if id[0] in _cmds['#']:
    id = _get_id_for_index(id)

  if id:
    gist = _get_gist(id)
    # display line delims only if more than one file exists. facilitates piping file content
    noDelim = len(gist['files']) == 1 or fileName != ''
    for (file, data) in list(gist['files'].items()):
      content = data['content']
      if not noDelim:
        util.line()
        print('Gist: {0} File: {1}'.format(id, file))
        util.line()
      if fileName != '':
        if fileName.strip().lower() == file.strip().lower():
          print(content)
      else:
        print(content)
      if not noDelim:
        util.line()
Exemple #10
0
def getCredentials():
    global token, username, password
    if os.path.exists(HOME + TOKENFILE):
        file = open(HOME + TOKENFILE, 'r')
        token = file.read().strip()
        log.debug("Credentials: " + HOME + TOKENFILE + " = " + token)
    elif os.path.exists(HOME + CREDENTIALS):
        file = open(HOME + CREDENTIALS, 'r')
        line = file.read().strip()
        token = line.split(':')[2].split('@')[0]
        log.debug("Credentials: " + HOME + CREDENTIALS + " = " + token)
    elif username == None or password == None:
        log.debug("Credentials: No token found.")
        username = input("Username: ")
        password = getpass.getpass()
        token = None
        auth(username, password)
Exemple #11
0
def supress( s ):
  global _supress
  _supress = s
  log.debug ("_supress: " + str(_supress))
Exemple #12
0
def isWindows():
  log.debug ("platform.system: {0} platform.machine: {1}".format(platform.system(), platform.machine()))
  return platform.system() == 'Windows'
Exemple #13
0
def isLinux ():
  log.debug ("platform.system: {0} platform.machine: {1}".format(platform.system(), platform.machine()))
  return platform.system() == 'Linux' or platform.system() == 'Linux2'
Exemple #14
0
def isMac ():
  log.debug ("platform.system: {0} platform.machine: {1}".format(platform.system(), platform.machine()))
  return platform.system() == 'Darwin' and not platform.machine().startswith('iP')
Exemple #15
0
def call(meth, path, data={}, params={}, headers={}):
    global token, username, password, authcode
    result = None
    url = GITHUB_API + path
    data = json.dumps(data)
    log.debug('Json data: ' + data)

    if meth == 'post' or meth == 'patch':
        headers['Content-type'] = 'application/x-www-form-urlencoded'
    if authcode:
        headers['X-GitHub-OTP'] = authcode
        log.debug('Using authcode.')

    try:
        if token != None:
            params['access_token'] = token
            if meth == 'get':
                request = requests.get(url, params=params, headers=headers)
            if meth == 'post':
                request = requests.post(url,
                                        params=params,
                                        data=data,
                                        headers=headers)
            if meth == 'patch':
                request = requests.patch(url,
                                         params=params,
                                         data=data,
                                         headers=headers)
            if meth == 'delete':
                request = requests.delete(url, params=params, headers=headers)
            log.debug('API ({0}): {1}'.format(meth, request.url))
        else:
            if meth == 'get':
                request = requests.get(url,
                                       auth=(username, password),
                                       params=params,
                                       headers=headers)
            if meth == 'post':
                request = requests.post(url,
                                        auth=(username, password),
                                        params=params,
                                        data=data,
                                        headers=headers)
            if meth == 'patch':
                request = requests.patch(url,
                                         auth=(username, password),
                                         params=params,
                                         data=data,
                                         headers=headers)
            if meth == 'delete':
                request = requests.delete(url,
                                          auth=(username, password),
                                          params=params,
                                          headers=headers)
            log.debug('API ({0}): {1}'.format(meth, request.url))

        _checkStatus(request)

        if meth != 'delete':
            result = json.loads(request.text)
    except Exception as e:
        print('Oops. We had a slight problem with the GitHub SSO: ' + str(e))
        sys.exit(0)
    return result
Exemple #16
0
def auth(username, password):
    global authcode
    log.debug('Authenticating ...')

    url = GITHUB_API + '/authorizations'

    request = requests.get(url, auth=(username, password))
    log.debug('request.status_code: {0}'.format(request.status_code))
    log.debug('request.text: {0}'.format(request.text))
    log.debug(request.headers)

    # 401 means unsuccessful basic auth
    if request.status_code == 401:
        # check if the OTP header exists... it should
        if 'X-GitHub-OTP' in request.headers:
            log.debug('OTP: {0}'.format(request.headers['X-GitHub-OTP']))
            # is OTP required?
            if request.headers['X-GitHub-OTP'].lower().find('required;') > -1:
                # If sms, request an sms and then prompt for code
                if request.headers['X-GitHub-OTP'].lower().find('sms') > -1:
                    print('Requesting SMS from GitHub ...')
                    request = requests.post(url, auth=(username, password))
                    log.debug('request.status_code: {0}'.format(
                        request.status_code))
                    log.debug('request.text: {0}'.format(request.text))
                    log.debug(request.headers)

                    if request.status_code == 401:
                        authcode = getpass.getpass(
                            'Two factor authentication code: ')
                    else:
                        print('Unable to request SMS from Github')
                # if not sms, assume application, prompt for code
                else:
                    log.debug('OTP code did not sms. Assume application...')
                    authcode = getpass.getpass(
                        'Two factor authentication code: ')
            else:
                log.debug('OTP not required.')
        else:
            print(
                'Github rejected the username and password but didnt send an OTP header. Try again please'
            )
    else:
        # username,pass accepted
        log.debug('Username and password accepted.')