Commits

Anonymous committed 5f6f9bb

Refatorado código utilizando exceções, ao invés de prints.

Criada função is_initialized e inserida em quase todas as verificações onde os.path.exists era utilizado. Comandos não implementados agora acionam a exceção NotImplementedError.

Comments (0)

Files changed (3)

engine/storage.py

         '''
         Returns the .seeti file as a file object.
         '''
-        try:
-            if os.path.exists(self.path):
-                return open(self.path, mode)
-        except IOError, e:
-            sys.stderr.write(e)
+        return open(self.path, mode)
     
     def init(self, hours=0, minutes=0):
         '''
                 yaml.dump(data, stream, default_flow_style=False)
                 print 'Seeti was successfully initialized!'
             else:
-                print 'Seeti was already initialized!'
+                raise RuntimeError('Seeti was already initialized!')
         except IOError:
-            sys.stderr.write("An error occurred while trying to create the .seeti file.\n"
-                             "Check if you've got write permissions on this directory.\n")
-    
-    def is_open(self):
-        '''
-        Returns True if there is a .seeti file and its 'open' field is set to True. 
-        Returns False otherwise.
-        '''
-        if os.path.exists(self.path):
-            try:
-                stream = list(yaml.load_all(self.load()))[0]
-                return stream.get('init').get('open', False)
-            except IOError, e:
-                sys.stderr.write(e)
-        return False
+            raise IOError("An error occurred while trying to create the .seeti file.\n"
+                          "Check if you've got write permissions on this directory.\n")
     
     def start(self):
         '''
         Creates a 'start' entry in .seeti file if already there isn't one, or if the last entry is a 'stop' one.
         '''
-        try:
-            if os.path.exists(self.path):
-                if self.is_open():
-                    if self.is_stopped():
-                        stream = self.load(mode='a')
-                        data = {'start': { 'datetime': datetime.datetime.now()}}
-                        yaml.dump(data, stream, default_flow_style=False, explicit_start=True)
-                        print 'Seeti started!'
-                    else:
-                        print "Seeti is already started!"
+        if self.is_initialized():
+            if self.is_open():
+                if self.is_stopped():
+                    stream = self.load(mode='a')
+                    data = {'start': { 'datetime': datetime.datetime.now()}}
+                    yaml.dump(data, stream, default_flow_style=False, explicit_start=True)
+                    print 'Seeti started!'
                 else:
-                    print "Seeti is closed. Open or restart the project, then execute the start command again."
+                    raise RuntimeError("Seeti is already started!")
             else:
-                print "Seeti was not initiated. You need to run the init command to do so."
-        except IOError:
-            sys.stderr.write("An error occurred while trying to save Seeti's data.")
+                raise RuntimeError("Seeti is closed. Open or restart the project, then execute the start command again.")
+        else:
+            raise RuntimeError("Seeti was not initiated. You need to run the init command to do so.")
     
-
-    def is_started(self):
-        '''
-        Returns True if the last entry is a 'start' one. Returns False otherwise.
-        '''
-        if os.path.exists(self.path):
-            try:
-                stream = list(yaml.load_all(self.load()))[-1]
-                return stream.has_key('start')
-            except IOError, e:
-                sys.stderr.write(e)
-        return False
-    
-    def is_stopped(self):
-        '''
-        Returns True if the last entry is a 'stop' one. Returns True otherwise.
-        '''
-        if os.path.exists(self.path):
-            try:
-                stream = list(yaml.load_all(self.load()))[-1]
-                return stream.has_key('stop') or not stream.has_key('start')
-            except IOError, e:
-                sys.stderr.write(e)
-        return False
                 
     def stop(self):
         '''
         Creates a 'stop' entry in .seeti file if the last entry is a 'start' one.
         '''
-        try:
-            if os.path.exists(self.path):
-                if self.is_open():
-                    if self.is_started():
-                        stream = self.load(mode='a')
-                        data = {'stop': { 'datetime': datetime.datetime.now()}}
-                        yaml.dump(data, stream, default_flow_style=False, explicit_start=True)
-                        print 'Seeti stopped!'
-                    else:
-                        print "Seeti is already stopped!"
+        if self.is_initialized():
+            if self.is_open():
+                if not self.is_stopped():
+                    stream = self.load(mode='a')
+                    data = {'stop': { 'datetime': datetime.datetime.now()}}
+                    yaml.dump(data, stream, default_flow_style=False, explicit_start=True)
+                    print 'Seeti stopped!'
                 else:
-                    print "Seeti is closed."
+                    raise RuntimeError("Seeti is already stopped!")
             else:
-                print "Seeti was not initiated. You need to run the init command to do so."
-        except IOError:
-            sys.stderr.write("An error occurred while trying to save Seeti's data.")
+                raise RuntimeError("Seeti is closed.")
+        else:
+            raise RuntimeError("Seeti was not initiated. You need to run the init command to do so.")
     
     def report(self):
         '''
         Computes the difference of all the 'start's and 'stops's, sums them and then displays the total.
         If the last command issued was a 'start', the last 'stop' is the current datetime.
         '''
-        try:
-            if os.path.exists(self.path):
-                starts = [ item.get('start').get('datetime') for item in yaml.load_all(self.load()) 
-                                    if item.has_key('start') ]
-                stops = [ item.get('stop').get('datetime') for item in yaml.load_all(self.load()) 
-                                    if item.has_key('stop') ]
+        if self.is_initialized():
+            starts = [ item.get('start').get('datetime') for item in yaml.load_all(self.load())
+                      if item.has_key('start') ]
+            stops = [ item.get('stop').get('datetime') for item in yaml.load_all(self.load())
+                      if item.has_key('stop') ]
                     
-                if self.is_started():
-                    stops.append(datetime.datetime.now())
+            if self.is_started():
+                stops.append(datetime.datetime.now())
                     
-                timedelta = datetime.timedelta()
+            timedelta = datetime.timedelta()
 
-                for i in xrange(len(starts)):
-                    timedelta += stops[i] - starts[i]
+            for i in xrange(len(starts)):
+                timedelta += stops[i] - starts[i]
                         
-                print "Time spent:", timedelta
-            else:
-                print "Seeti was not initiated. You need to run the init command to do so."
-        except IOError:
-            sys.stderr.write("An error occurred while trying to save Seeti's data.")
+            print 'Time spent:', timedelta
+        else:
+            raise RuntimeError("Seeti was not initiated. You need to run the init command to do so.")
             
     def status(self):
         '''
                         'init': 'initialized',
                         # Not implemented yet
                         'close': 'closed'} 
-            try:
-                stream = tuple(yaml.load_all(self.load()))[-1]
+        stream = tuple(yaml.load_all(self.load()))[-1]
 
-                print 'Status: %s' % statuses.get(tuple(stream)[0], 'unknown')
-            except IOError, e:
-                sys.stderr.write(e)
+        print 'Status: %s' % statuses.get(tuple(stream)[0], 'unknown')
+    
+    def close(self):
+        raise NotImplementedError()
+    
+    def open(self):
+        raise NotImplementedError()
+    
+    def restart(self):
+        raise NotImplementedError()
+    
+    def is_initialized(self):
+        '''
+        Returns True if there is a .seeti file and there's an 'init' entry on it. 
+        Returns False otherwise.
+        '''
+        if os.path.exists(self.path):
+            stream = tuple(yaml.load_all(self.load()))[0]
+            return stream.has_key('init')
+            
         return False
     
-    def close(self):
-        raise NotImplementedError("This command was not implemented... yet.")
+    def is_open(self):
+        '''
+        Returns True if there is a .seeti file and its 'open' field is set to True. 
+        Returns False otherwise.
+        '''
+        if self.is_initialized():
+            stream = tuple(yaml.load_all(self.load()))[0]
+            return stream.get('init').get('open', False)
+
+        return False
     
-    def open(self):
-        raise NotImplementedError("This command was not implemented... yet.")
+    def is_started(self):
+        '''
+        Returns True if the last entry is a 'start' one. Returns False otherwise.
+        '''
+        if self.is_initialized():
+            stream = list(yaml.load_all(self.load()))[-1]
+            return stream.has_key('start')
+        
+        return False
     
-    def restart(self):
-        raise NotImplementedError("This command was not implemented... yet.")
-    
+    def is_stopped(self):
+        '''
+        Returns True if the last entry is a 'stop' one. Returns True otherwise.
+        '''
+        if self.is_initialized():
+            stream = list(yaml.load_all(self.load()))[-1]
+            return stream.has_key('stop') or not stream.has_key('start')
+        
+        return False

engine/storage.pyc

Binary file modified.
         elif args.get('open'):
             manager.open()
     except NotImplementedError as e:
-        print e
+        print "Command not implemented yet."
     except RuntimeError as e:
         print e
     except Exception as e: