Skip to content

Commit

Permalink
Fixes/Implements #204: Return non-zero error code on error
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Naudus committed Jun 25, 2014
1 parent 192a0c5 commit 052d147
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 54 deletions.
2 changes: 1 addition & 1 deletion geeknote/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
os.mkdir(APP_DIR)
except Exception, e:
sys.stdout.write("Can not create application dirictory : %s" % APP_DIR)
exit()
exit(1)

if DEV_MODE:
USER_STORE_URI = USER_STORE_URI_SANDBOX
Expand Down
2 changes: 1 addition & 1 deletion geeknote/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def textToENML(content, raise_ex=False, format='markdown'):
"Content must be an UTF-8 encode.")
out.failureMessage("Error while parsing text to html. "
"Content must be an UTF-8 encode.")
return tools.exit()
return tools.exitErr()

def __init__(self, content):
if not isinstance(content, str):
Expand Down
50 changes: 27 additions & 23 deletions geeknote/geeknote.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def wrapper(*args, **kwargs):

if not hasattr(e, 'errorCode'):
out.failureMessage("Sorry, operation has failed!!!.")
tools.exit()
tools.exitErr()

errorCode = int(e.errorCode)

Expand All @@ -87,7 +87,7 @@ def wrapper(*args, **kwargs):
else:
return False

tools.exit()
tools.exitErr()

return wrapper

Expand Down Expand Up @@ -127,7 +127,7 @@ def checkVersion(self):
UserStoreConstants.EDAM_VERSION_MINOR)
if not versionOK:
logging.error("Old EDAM version")
return tools.exit()
return tools.exitErr()

def checkAuth(self):
self.authToken = self.getStorage().getUserToken()
Expand Down Expand Up @@ -321,7 +321,7 @@ class User(GeekNoteConnector):
def user(self, full=None):
if not self.getEvernote().checkAuth():
out.failureMessage("You not logged in.")
return tools.exit()
return tools.exitErr()

if full:
info = self.getEvernote().getUserInfo()
Expand All @@ -332,20 +332,20 @@ def user(self, full=None):
@GeekNoneDBConnectOnly
def login(self):
if self.getEvernote().checkAuth():
out.successMessage("You have already logged in.")
return tools.exit()
out.failureMessage("You have already logged in.")
return tools.exitErr()

if self.getEvernote().auth():
out.successMessage("You have successfully logged in.")
else:
out.failureMessage("Login error.")
return tools.exit()
return tools.exitErr()

@GeekNoneDBConnectOnly
def logout(self, force=None):
if not self.getEvernote().checkAuth():
out.successMessage("You have already logged out.")
return tools.exit()
out.failureMessage("You have already logged out.")
return tools.exitErr()

if not force and not out.confirm('Are you sure you want to logout?'):
return tools.exit()
Expand All @@ -355,7 +355,7 @@ def logout(self, force=None):
out.successMessage("You have successfully logged out.")
else:
out.failureMessage("Logout error.")
return tools.exit()
return tools.exitErr()

@GeekNoneDBConnectOnly
def settings(self, editor=None):
Expand Down Expand Up @@ -405,7 +405,7 @@ def create(self, title):
out.successMessage("Tag has been successfully created.")
else:
out.failureMessage("Error while the process of creating the tag.")
return tools.exit()
return tools.exitErr()

return result

Expand All @@ -419,7 +419,7 @@ def edit(self, tagname, title):
out.successMessage("Tag has been successfully updated.")
else:
out.failureMessage("Error while the updating the tag.")
return tools.exit()
return tools.exitErr()

def remove(self, tagname, force=None):
tag = self._searchTag(tagname)
Expand Down Expand Up @@ -466,7 +466,7 @@ def create(self, title):
else:
out.failureMessage("Error while the process "
"of creating the notebook.")
return tools.exit()
return tools.exitErr()

return result

Expand All @@ -481,7 +481,7 @@ def edit(self, notebook, title):
out.successMessage("Notebook has been successfully updated.")
else:
out.failureMessage("Error while the updating the notebook.")
return tools.exit()
return tools.exitErr()

def remove(self, notebook, force=None):
notebook = self._searchNotebook(notebook)
Expand Down Expand Up @@ -690,8 +690,8 @@ def _searchNote(self, note):

logging.debug("Search notes result: %s" % str(result))
if result.totalNotes == 0:
out.successMessage("Notes have not been found.")
return tools.exit()
out.failureMessage("Notes have not been found.")
return tools.exitErr()

elif result.totalNotes == 1 or self.selectFirstOnUpdate:
note = result.notes[0]
Expand Down Expand Up @@ -735,7 +735,8 @@ def find(self, search=None, tags=None, notebooks=None,
count = update_count(count)

if result.totalNotes == 0:
out.successMessage("Notes have not been found.")
out.failureMessage("Notes have not been found.")
return tools.exitErr()

# save search result
# print result
Expand Down Expand Up @@ -774,7 +775,7 @@ def _createSearchRequest(self, search=None, tags=None,
except ValueError, e:
out.failureMessage('Incorrect date format in --date attribute. '
'Format: %s' % time.strftime("%d.%m.%Y", time.strptime('19991231', "%Y%m%d")))
return tools.exit()
return tools.exitErr()

if search:
search = tools.strip(search)
Expand All @@ -797,13 +798,13 @@ def modifyArgsByStdinStream():

if not content:
out.failureMessage("Input stream is empty.")
return tools.exit()
return tools.exitErr()

title = ' '.join(content.split(' ', 5)[:-1])
title = re.sub(r'(\r\n|\r|\n)', r' ', title)
if not title:
out.failureMessage("Error while creating title of note from stream.")
return tools.exit()
return tools.exitErr()
elif len(title) > 50:
title = title[0:50] + '...'

Expand All @@ -817,6 +818,8 @@ def modifyArgsByStdinStream():

def main(args=None):
try:
exitStatusCode = 0

# if terminal
if config.IS_IN_TERMINAL:
sys_argv = sys.argv[1:]
Expand Down Expand Up @@ -895,15 +898,16 @@ def main(args=None):
if COMMAND == 'tag-remove':
Tags().remove(**ARGS)

except (KeyboardInterrupt, SystemExit, tools.ExitException):
pass
except (KeyboardInterrupt, SystemExit, tools.ExitException), e:
if e.message:
exitStatusCode = e.message

except Exception, e:
traceback.print_exc()
logging.error("App error: %s", str(e))

# exit preloader
tools.exit()
tools.exit('exit', exitStatusCode)

if __name__ == "__main__":
main()
22 changes: 11 additions & 11 deletions geeknote/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def getTokenRequestData(self, **kwargs):
def loadPage(self, url, uri=None, method="GET", params=""):
if not url:
logging.error("Request URL undefined")
tools.exit()
tools.exitErr()

if not uri:
urlData = urlparse(url)
Expand Down Expand Up @@ -149,12 +149,12 @@ def getTmpOAuthToken(self):
if response.status != 200:
logging.error("Unexpected response status on get "
"temporary oauth_token 200 != %s", response.status)
tools.exit()
tools.exitErr()

responseData = self.parseResponse(response.data)
if 'oauth_token' not in responseData:
logging.error("OAuth temporary not found")
tools.exit()
tools.exitErr()

self.tmpOAuthToken = responseData['oauth_token']

Expand All @@ -176,7 +176,7 @@ def handleTwoFactor(self):

if not response.location:
logging.error("Target URL was not found in the response on login")
tools.exit()
tools.exitErr()

def login(self):
response = self.loadPage(self.url['base'],
Expand All @@ -187,11 +187,11 @@ def login(self):
if response.status != 200:
logging.error("Unexpected response status "
"on login 200 != %s", response.status)
tools.exit()
tools.exitErr()

if 'JSESSIONID' not in self.cookies:
logging.error("Not found value JSESSIONID in the response cookies")
tools.exit()
tools.exitErr()

# get login/password
self.username, self.password = out.GetUserCredentials()
Expand All @@ -216,7 +216,7 @@ def login(self):

if not response.location:
logging.error("Target URL was not found in the response on login")
tools.exit()
tools.exitErr()

if response.status == 302:
# the user has enabled two factor auth
Expand All @@ -238,12 +238,12 @@ def allowAccess(self):
if response.status != 302:
logging.error("Unexpected response status on allowing "
"access 302 != %s", response.status)
tools.exit()
tools.exitErr()

responseData = self.parseResponse(response.location)
if 'oauth_verifier' not in responseData:
logging.error("OAuth verifier not found")
tools.exit()
tools.exitErr()

self.verifierToken = responseData['oauth_verifier']

Expand All @@ -262,12 +262,12 @@ def getOAuthToken(self):
if response.status != 200:
logging.error("Unexpected response status on "
"getting oauth token 200 != %s", response.status)
tools.exit()
tools.exitErr()

responseData = self.parseResponse(response.data)
if 'oauth_token' not in responseData:
logging.error("OAuth token not found")
tools.exit()
tools.exitErr()

logging.debug("OAuth token take : %s", responseData['oauth_token'])
self.OAuthToken = responseData['oauth_token']
46 changes: 31 additions & 15 deletions geeknote/out.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

import getpass
import threading
import thread
import time
import sys
Expand Down Expand Up @@ -69,9 +70,13 @@ def stop():
preloader.isLaunch = False

@staticmethod
def exit():
def exit(code=0):
preloader.stop()
thread.exit()

if threading.current_thread().__class__.__name__ == '_MainThread':
sys.exit(code)
else:
thread.exit()

@staticmethod
def draw():
Expand Down Expand Up @@ -100,8 +105,11 @@ def GetUserCredentials():

if password is None:
password = rawInput("Password: ", True)
except (KeyboardInterrupt, SystemExit):
tools.exit()
except (KeyboardInterrupt, SystemExit), e:
if e.message:
tools.exit(e.message)
else:
tools.exit

return (login, password)

Expand All @@ -112,8 +120,11 @@ def GetUserAuthCode():
code = None
if code is None:
code = rawInput("Two-Factor Authentication Code: ")
except (KeyboardInterrupt, SystemExit):
tools.exit()
except (KeyboardInterrupt, SystemExit), e:
if e.message:
tools.exit(e.message)
else:
tools.exit

return code

Expand Down Expand Up @@ -142,8 +153,11 @@ def confirm(message):
return False
failureMessage('Incorrect answer "%s", '
'please try again:\n' % answer)
except (KeyboardInterrupt, SystemExit):
tools.exit()
except (KeyboardInterrupt, SystemExit), e:
if e.message:
tools.exit(e.message)
else:
tools.exit


@preloaderStop
Expand Down Expand Up @@ -189,8 +203,7 @@ def successMessage(message):
@preloaderStop
def failureMessage(message):
""" Displaying a message."""
printLine(message, "\n")

printLine(message, "\n", sys.stderr)

def separator(symbol="", title=""):
size = 40
Expand Down Expand Up @@ -238,8 +251,11 @@ def printList(listItems, title="", showSelector=False,
exit(1)
failureMessage('Incorrect number "%s", '
'please try again:\n' % num)
except (KeyboardInterrupt, SystemExit):
tools.exit()
except (KeyboardInterrupt, SystemExit), e:
if e.message:
tools.exit(e.message)
else:
tools.exit


def rawInput(message, isPass=False):
Expand All @@ -253,14 +269,14 @@ def rawInput(message, isPass=False):
def printDate(timestamp):
return time.strftime("%d/%m/%Y %H:%M", time.localtime(timestamp/1000))

def printLine(line, endLine="\n"):
def printLine(line, endLine="\n", out=sys.stdout):
message = line + endLine
message = tools.stdoutEncode(message)
try:
sys.stdout.write(message)
out.write(message)
except:
pass
sys.stdout.flush()
out.flush()


def printAbout():
Expand Down
Loading

0 comments on commit 052d147

Please sign in to comment.