PEP8 Cleanup

master
Andrew Williams 2014-11-15 19:45:52 +00:00
parent 7e226f2255
commit 0b023789a7
1 changed files with 342 additions and 335 deletions

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
import copy
import dateutil.parser import dateutil.parser
import dateutil.tz import dateutil.tz
import datetime import datetime
@ -15,8 +14,10 @@ API_TOKEN = os.environ.get('TODOIST_API_KEY', None)
NEXT_ACTION_LABEL = os.environ.get('TODOIST_NEXT_ACTION_LABEL', 'next_action') NEXT_ACTION_LABEL = os.environ.get('TODOIST_NEXT_ACTION_LABEL', 'next_action')
TODOIST_VERSION = '5.3' TODOIST_VERSION = '5.3'
class TraversalState(object): class TraversalState(object):
"""Simple class to contain the state of the item tree traversal.""" """Simple class to contain the state of the item tree traversal."""
def __init__(self, next_action_label_id): def __init__(self, next_action_label_id):
self.remove_labels = [] self.remove_labels = []
self.add_labels = [] self.add_labels = []
@ -54,7 +55,7 @@ class Item(object):
self.item_id = initial_data['id'] self.item_id = initial_data['id']
self.labels = initial_data['labels'] self.labels = initial_data['labels']
self.priority = initial_data['priority'] self.priority = initial_data['priority']
if 'due_date_utc' in initial_data and initial_data['due_date_utc'] != None: if 'due_date_utc' in initial_data and initial_data['due_date_utc'] is not None:
p = dateutil.parser.parser() p = dateutil.parser.parser()
self.due_date_utc = p.parse(initial_data['due_date_utc']) self.due_date_utc = p.parse(initial_data['due_date_utc'])
else: else:
@ -119,6 +120,7 @@ class Item(object):
#else: #else:
# return self.parent.IsParallel() # return self.parent.IsParallel()
class Project(object): class Project(object):
def __init__(self, initial_data): def __init__(self, initial_data):
self._todoist = None self._todoist = None
@ -138,16 +140,16 @@ class Project(object):
self.SortChildren() self.SortChildren()
def getItems(self): def getItems(self):
req = urllib2.Request('https://todoist.com/API/getUncompletedItems?project_id='+ str(self.project_id) +'&token=' + API_TOKEN) req = urllib2.Request(
'https://todoist.com/API/getUncompletedItems?project_id=' + str(self.project_id) + '&token=' + API_TOKEN)
response = urllib2.urlopen(req) response = urllib2.urlopen(req)
return json.loads(response.read()) return json.loads(response.read())
def setTodoist(self, todoist): def setTodoist(self, todoist):
self._todoist = todoist self._todoist = todoist
def subProjects(self): def subProjects(self):
if self._subProjects == None: if self._subProjects is None:
self._subProjects = [] self._subProjects = []
initialIndent = self.indent initialIndent = self.indent
initialOrder = self._todoist._orderedProjects.index(self) initialOrder = self._todoist._orderedProjects.index(self)
@ -155,12 +157,12 @@ class Project(object):
maxSize = len(self._todoist._orderedProjects) maxSize = len(self._todoist._orderedProjects)
if order < maxSize: if order < maxSize:
current = self._todoist._orderedProjects[order] current = self._todoist._orderedProjects[order]
while ((current.indent > initialIndent) and (order < maxSize)): while (current.indent > initialIndent) and (order < maxSize):
current = self._todoist._orderedProjects[order] current = self._todoist._orderedProjects[order]
if current != None: if current != None:
self._subProjects.append(current) self._subProjects.append(current)
current.parent = self current.parent = self
order = order + 1 order += 1
return self._subProjects return self._subProjects
@ -170,8 +172,8 @@ class Project(object):
def IsSequential(self): def IsSequential(self):
ignored = self.IsIgnored() ignored = self.IsIgnored()
endsWithEqual = self.name.endswith('=') endsWithEqual = self.name.endswith('=')
validParent = self.parent == None or not self.parent.IsIgnored() validParent = self.parent is None or not self.parent.IsIgnored()
seq = ((not ignored) and (not endsWithEqual)) and validParent seq = (not ignored) and (not endsWithEqual) and validParent
# if self.name .startsWith('Payer Camille'): # if self.name .startsWith('Payer Camille'):
# print startsWithKeyword # print startsWithKeyword
# print endsWithEqual # print endsWithEqual
@ -199,7 +201,7 @@ class Project(object):
item.GetLabelRemovalMods(state) item.GetLabelRemovalMods(state)
def _CreateItemTree(self, items): def _CreateItemTree(self, items):
'''Build a tree of items based on their indentation level.''' """Build a tree of items based on their indentation level."""
parent_item = self parent_item = self
previous_item = self previous_item = self
for item_dict in items: for item_dict in items:
@ -209,20 +211,21 @@ class Project(object):
previous_item.content, parent_item.content) previous_item.content, parent_item.content)
parent_item = previous_item parent_item = previous_item
# walk up the tree until we reach our parent # walk up the tree until we reach our parent
while (parent_item.parent != None and item.indent <= parent_item.indent): while parent_item.parent is not None and item.indent <= parent_item.indent:
logging.debug('walking up the tree from "%s" to "%s"', logging.debug('walking up the tree from "%s" to "%s"',
parent_item.content, (parent_item.parent if (parent_item.parent != None) else 0)) parent_item.content, (parent_item.parent if (parent_item.parent is not None) else 0))
parent_item = parent_item.parent parent_item = parent_item.parent
logging.debug('adding item "%s" with parent "%s"', item.content, logging.debug('adding item "%s" with parent "%s"', item.content,
parent_item.content if (parent_item != None) else '') parent_item.content if (parent_item is not None) else '')
parent_item.children.append(item) parent_item.children.append(item)
item.parent = parent_item item.parent = parent_item
previous_item = item previous_item = item
class TodoistData(object): class TodoistData(object):
'''Construct an object based on a full Todoist /Get request's data''' """Construct an object based on a full Todoist /Get request's data"""
def __init__(self, initial_data): def __init__(self, initial_data):
self._SetLabelData(initial_data) self._SetLabelData(initial_data)
self._projects = dict() self._projects = dict()
@ -245,7 +248,7 @@ class TodoistData(object):
if label['name'] == NEXT_ACTION_LABEL: if label['name'] == NEXT_ACTION_LABEL:
self._next_action_id = label['id'] self._next_action_id = label['id']
logging.info('Found next_action label, id: %s', label['id']) logging.info('Found next_action label, id: %s', label['id'])
if self._next_action_id == None: if self._next_action_id is None:
logging.warning('Failed to find next_action label, need to create it.') logging.warning('Failed to find next_action label, need to create it.')
def GetSyncState(self): def GetSyncState(self):
@ -287,11 +290,10 @@ class TodoistData(object):
project.last_updated = timestamp project.last_updated = timestamp
def GetProjectMods(self): def GetProjectMods(self):
mods = [] mods = []
# We need to create the next_action label # We need to create the next_action label
if self._next_action_id == None: if self._next_action_id is None:
self._next_action_id = '$%d' % int(time.time()) self._next_action_id = '$%d' % int(time.time())
mods.append({'type': 'label_register', mods.append({'type': 'label_register',
'timestamp': int(time.time()), 'timestamp': int(time.time()),
@ -335,21 +337,23 @@ class TodoistData(object):
return mods return mods
def GetResponse(): def GetResponse():
values = {'api_token': API_TOKEN, 'resource_types': ['labels']} values = {'api_token': API_TOKEN, 'resource_types': ['labels']}
data = urllib.urlencode(values) data = urllib.urlencode(values)
req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/get', data) req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/get', data)
return urllib2.urlopen(req) return urllib2.urlopen(req)
def GetLabels(): def GetLabels():
req = urllib2.Request('https://todoist.com/API/getLabels?token=' + API_TOKEN) req = urllib2.Request('https://todoist.com/API/getLabels?token=' + API_TOKEN)
return urllib2.urlopen(req) return urllib2.urlopen(req)
def GetProjects(): def GetProjects():
req = urllib2.Request('https://todoist.com/API/getProjects?token=' + API_TOKEN) req = urllib2.Request('https://todoist.com/API/getProjects?token=' + API_TOKEN)
return urllib2.urlopen(req) return urllib2.urlopen(req)
def DoSync(items_to_sync): def DoSync(items_to_sync):
values = {'api_token': API_TOKEN, values = {'api_token': API_TOKEN,
'items_to_sync': json.dumps(items_to_sync)} 'items_to_sync': json.dumps(items_to_sync)}
@ -358,6 +362,7 @@ def DoSync(items_to_sync):
req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/sync', data) req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/sync', data)
return urllib2.urlopen(req) return urllib2.urlopen(req)
def DoSyncAndGetUpdated(items_to_sync, sync_state): def DoSyncAndGetUpdated(items_to_sync, sync_state):
values = {'api_token': API_TOKEN, values = {'api_token': API_TOKEN,
'items_to_sync': json.dumps(items_to_sync)} 'items_to_sync': json.dumps(items_to_sync)}
@ -368,6 +373,7 @@ def DoSyncAndGetUpdated(items_to_sync, sync_state):
req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/syncAndGetUpdated', data) req = urllib2.Request('https://api.todoist.com/TodoistSync/v' + TODOIST_VERSION + '/syncAndGetUpdated', data)
return urllib2.urlopen(req) return urllib2.urlopen(req)
def main(): def main():
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
response = GetResponse() response = GetResponse()
@ -396,5 +402,6 @@ def main():
logging.info("* Finished updating model") logging.info("* Finished updating model")
logging.info("** Finished sync") logging.info("** Finished sync")
if __name__ == '__main__': if __name__ == '__main__':
main() main()