opener: introduce tryread helper
authorMatt Mackall <mpm@selenic.com>
Tue, 17 Apr 2012 11:11:59 -0500
changeset 16455 154219f3a6a4
parent 16454 92c7e917b647
child 16456 42862d64aa8f
opener: introduce tryread helper This makes it easier to follow the common pattern "read a file or give an empty string if it's missing".
mercurial/scmutil.py
--- a/mercurial/scmutil.py	Tue Apr 17 07:22:44 2012 +0200
+++ b/mercurial/scmutil.py	Tue Apr 17 11:11:59 2012 -0500
@@ -159,6 +159,15 @@
         '''Prevent instantiation; don't call this from subclasses.'''
         raise NotImplementedError('attempted instantiating ' + str(type(self)))
 
+    def tryread(self, path):
+        'gracefully return an empty string for missing files'
+        try:
+            return self.read(path)
+        except IOError, inst:
+            if inst.errno != errno.ENOENT:
+                raise
+        return ""
+
     def read(self, path):
         fp = self(path, 'rb')
         try: