[util] improve compatibility with WSL

This commit is contained in:
Fangzhou Li 2018-07-16 04:22:13 +08:00
parent a07ba1a5df
commit 50216593e4
3 changed files with 38 additions and 7 deletions

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python #!/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. """Converts a string to a valid filename.
""" """
@ -13,7 +13,7 @@ def legitimize(text, os=platform.system()):
ord('|'): '-', ord('|'): '-',
}) })
if os == 'Windows': if os == 'windows' or os == 'cygwin' or os == 'wsl':
# Windows (non-POSIX namespace) # Windows (non-POSIX namespace)
text = text.translate({ text = text.translate({
# Reserved in Windows VFAT and NTFS # Reserved in Windows VFAT and NTFS
@ -31,7 +31,7 @@ def legitimize(text, os=platform.system()):
}) })
else: else:
# *nix # *nix
if os == 'Darwin': if os == 'mac':
# Mac OS HFS+ # Mac OS HFS+
text = text.translate({ text = text.translate({
ord(':'): '-', ord(':'): '-',

30
src/you_get/util/os.py Normal file
View File

@ -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

View File

@ -6,6 +6,7 @@ from you_get.util.fs import *
class TestUtil(unittest.TestCase): class TestUtil(unittest.TestCase):
def test_legitimize(self): def test_legitimize(self):
self.assertEqual(legitimize("1*2", os="Linux"), "1*2") self.assertEqual(legitimize("1*2", os="linux"), "1*2")
self.assertEqual(legitimize("1*2", os="Darwin"), "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="windows"), "1-2")
self.assertEqual(legitimize("1*2", os="wsl"), "1-2")