From 50216593e439b6e940e868a9f98c4475ee3636f5 Mon Sep 17 00:00:00 2001 From: Fangzhou Li Date: Mon, 16 Jul 2018 04:22:13 +0800 Subject: [PATCH] [util] improve compatibility with WSL --- src/you_get/util/fs.py | 8 ++++---- src/you_get/util/os.py | 30 ++++++++++++++++++++++++++++++ tests/test_util.py | 7 ++++--- 3 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 src/you_get/util/os.py diff --git a/src/you_get/util/fs.py b/src/you_get/util/fs.py index d49a117d..b6b7069a 100644 --- a/src/you_get/util/fs.py +++ b/src/you_get/util/fs.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -import platform +from .os import detect_os -def legitimize(text, os=platform.system()): +def legitimize(text, os=detect_os()): """Converts a string to a valid filename. """ @@ -13,7 +13,7 @@ def legitimize(text, os=platform.system()): ord('|'): '-', }) - if os == 'Windows': + if os == 'windows' or os == 'cygwin' or os == 'wsl': # Windows (non-POSIX namespace) text = text.translate({ # Reserved in Windows VFAT and NTFS @@ -31,7 +31,7 @@ def legitimize(text, os=platform.system()): }) else: # *nix - if os == 'Darwin': + if os == 'mac': # Mac OS HFS+ text = text.translate({ ord(':'): '-', diff --git a/src/you_get/util/os.py b/src/you_get/util/os.py new file mode 100644 index 00000000..11730e28 --- /dev/null +++ b/src/you_get/util/os.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python + +from platform import system + +def detect_os(): + """Detect operating system. + """ + + # Inspired by: + # https://github.com/scivision/pybashutils/blob/78b7f2b339cb03b1c37df94015098bbe462f8526/pybashutils/windows_linux_detect.py + + syst = system().lower() + os = 'unknown' + + if 'cygwin' in syst: + os = 'cygwin' + elif 'darwin' in syst: + os = 'mac' + elif 'linux' in syst: + os = 'linux' + # detect WSL https://github.com/Microsoft/BashOnWindows/issues/423 + with open('/proc/version', 'r') as f: + if 'microsoft' in f.read().lower(): + os = 'wsl' + elif 'windows' in syst: + os = 'windows' + elif 'bsd' in syst: + os = 'bsd' + + return os diff --git a/tests/test_util.py b/tests/test_util.py index 239083bc..88743b03 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -6,6 +6,7 @@ from you_get.util.fs import * class TestUtil(unittest.TestCase): def test_legitimize(self): - self.assertEqual(legitimize("1*2", os="Linux"), "1*2") - self.assertEqual(legitimize("1*2", os="Darwin"), "1*2") - self.assertEqual(legitimize("1*2", os="Windows"), "1-2") + self.assertEqual(legitimize("1*2", os="linux"), "1*2") + self.assertEqual(legitimize("1*2", os="mac"), "1*2") + self.assertEqual(legitimize("1*2", os="windows"), "1-2") + self.assertEqual(legitimize("1*2", os="wsl"), "1-2")