78a1340b652d

Intercept common IO errors exceptions.

When the task directory doesn't exist or when a file can't be read or written,
t.py fails with a full stacktrace exception. This change allows t.py to fail
more gracefully, printing the exception message, the relevant file, and then
exiting with an errorlevel code of 1.

# Non existant directory issue
/home/dereckson/dev/t ] ./t.py -t /nonexistent Lorem ipsum dolor
No such file or directory - /nonexistent/tasks

# File permission issue
/home/dereckson/dev/t ] mkdir test
/home/dereckson/dev/t ] ./t.py -t test Lorem ipsum dolor
/home/dereckson/dev/t ] chmod 000 test/.tasks.done
/home/dereckson/dev/t ] ./t.py -t test Lorem ipsum dolor
Permission denied - test/.tasks.done
[view raw] [browse files]
author Dereckson
date Sat, 31 Aug 2013 10:31:43 +0200
parents 1c496e933168
children bc7821308e0b
branches/tags (none)
files t.py

Changes

--- a/t.py	Tue Oct 09 13:46:00 2012 -0400
+++ b/t.py	Sat Aug 31 10:31:43 2013 +0200
@@ -134,12 +134,15 @@
             if os.path.isdir(path):
                 raise InvalidTaskfile
             if os.path.exists(path):
-                with open(path, 'r') as tfile:
-                    tls = [tl.strip() for tl in tfile if tl]
-                    tasks = map(_task_from_taskline, tls)
-                    for task in tasks:
-                        if task is not None:
-                            getattr(self, kind)[task['id']] = task
+		try:
+	                with open(path, 'r') as tfile:
+        	            tls = [tl.strip() for tl in tfile if tl]
+                	    tasks = map(_task_from_taskline, tls)
+	                    for task in tasks:
+        	                if task is not None:
+                	            getattr(self, kind)[task['id']] = task
+		except IOError as e:
+			sys.exit(e.strerror + ' - ' + path)
 
     def __getitem__(self, prefix):
         """Return the unfinished task with the given prefix.
@@ -230,9 +233,13 @@
                 raise InvalidTaskfile
             tasks = sorted(getattr(self, kind).values(), key=itemgetter('id'))
             if tasks or not delete_if_empty:
-                with open(path, 'w') as tfile:
-                    for taskline in _tasklines_from_tasks(tasks):
-                        tfile.write(taskline)
+		try:
+        	        with open(path, 'w') as tfile:
+       	        	    for taskline in _tasklines_from_tasks(tasks):
+				tfile.write(taskline)
+		except IOError as e:
+			sys.exit(e.strerror + ' - ' + path)
+
             elif not tasks and os.path.isfile(path):
                 os.remove(path)