Commits

Anonymous committed 04c5899

Refactored serialization script.

Comments (0)

Files changed (1)

MoinMoin/script/maint/serialization.py

 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.'
     ]
 
     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)
 
 
     ]
 
     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)
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.