changeset 1322:04c5899fc02b

Refactored serialization script.
author "Miks Kalnins <MiksKalnins@MaikuMori.com>"
date Mon, 09 Apr 2012 02:10:57 +0300
parents cc7067f61939
children 79ec6223a86c
files MoinMoin/script/maint/serialization.py
diffstat 1 files changed, 21 insertions(+), 20 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/script/maint/serialization.py	Sun Apr 08 15:15:13 2012 +0300
+++ b/MoinMoin/script/maint/serialization.py	Mon Apr 09 02:10:57 2012 +0300
@@ -16,6 +16,25 @@
 from MoinMoin import log
 logging = log.getLogger(__name__)
 
+def open_file(filename, mode):
+    if filename is None:
+        # Guess the IO stream from the mode:
+        if "a" in mode or "w" in mode:
+            stream = sys.stdout
+        elif "r" in mode:
+            stream = sys.stdin
+        else:
+            raise ValueError("Invalid mode string. Must contain 'r', 'w' or 'a'")
+        
+        # On Windows force the stream to be in binary mode if it's needed.
+        if sys.platform == "win32" and "b" in mode:
+            import os, msvcrt
+            msvcrt.setmode(stream.fileno(), os.O_BINARY)
+
+        f = stream
+    else:
+        f = open(filename, mode)
+    return f
 
 class Serialize(Command):
     description = 'Serialize the backend into a file.'
@@ -26,16 +45,7 @@
     ]
 
     def run(self, filename=None):
-        if filename is None:
-            # On Windows force the stdout to be in binary mode.
-            if sys.platform == "win32":
-                import os, msvcrt
-                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
-
-            f = sys.stdout
-        else:
-            f = open(filename, "wb")
-        with f as f:
+        with open_file(filename, "wb") as f:
             serialize(app.storage.backend, f)
 
 
@@ -48,15 +58,6 @@
     ]
 
     def run(self, filename=None):
-        if filename is None:
-            # On Windows force the stdin to be in binary mode.
-            if sys.platform == "win32":
-                import os, msvcrt
-                msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
-
-            f = sys.stdin
-        else:
-            f = open(filename, "rb")
-        with f as f:
+        with open_file(filename, "rb") as f:
             deserialize(f, app.storage.backend)