Windows symlink: extract all system depended code to System static class

This commit is contained in:
Dmitry Petrov
2017-04-10 21:04:40 -07:00
parent 8b024eba53
commit 4578b6aeb4
16 changed files with 147 additions and 137 deletions
-5
View File
@@ -1,5 +0,0 @@
from dvc.runtime import Runtime
def setup():
Runtime.symlink_setup()
+2 -3
View File
@@ -3,8 +3,7 @@ import os
from dvc.config import ConfigError
from dvc.logger import Logger
from dvc.path.factory import PathFactory
from dvc.utils import cached_property
from dvc.system import System
class CmdBase(object):
@@ -89,7 +88,7 @@ class CmdBase(object):
pass
def get_cache_file_s3_name(self, cache_file):
cache_prefix_file_name = os.path.relpath(os.path.realpath(cache_file), os.path.realpath(self.git.git_dir))
cache_prefix_file_name = os.path.relpath(System.realpath(cache_file), System.realpath(self.git.git_dir))
file_name = os.path.relpath(cache_prefix_file_name, self.config.cache_dir)
dvc_file_path_trim = file_name.replace(os.sep, '/').strip('/')
return self.config.aws_storage_prefix + '/' + dvc_file_path_trim
+3 -2
View File
@@ -7,6 +7,7 @@ from dvc.command.base import CmdBase
from dvc.logger import Logger
from dvc.exceptions import DvcException
from dvc.runtime import Runtime
from dvc.system import System
class DataSyncError(DvcException):
@@ -52,7 +53,7 @@ class CmdDataSync(CmdBase):
pass
def run(self):
if os.path.islink(self.parsed_args.target):
if System.islink(self.parsed_args.target):
data_item = self.path_factory.existing_data_item(self.parsed_args.target)
return self.sync_symlink(data_item)
@@ -66,7 +67,7 @@ class CmdDataSync(CmdBase):
fname = os.path.join(dir, f)
if os.path.isdir(fname):
self.sync_dir(fname)
elif os.path.islink(fname):
elif System.islink(fname):
self.sync_symlink(self.path_factory.existing_data_item(fname))
else:
raise DataSyncError('Unsupported file type "{}"'.format(fname))
+4 -24
View File
@@ -1,10 +1,9 @@
import os
if os.name == 'nt':
from ctypes import create_unicode_buffer, windll
from dvc.logger import Logger
from dvc.config import Config
from dvc.executor import Executor, ExecutorError
from dvc.system import System
class GitWrapperI(object):
@@ -22,7 +21,7 @@ class GitWrapperI(object):
@property
def git_dir_abs(self):
return os.path.realpath(self.git_dir)
return System.realpath(self.git_dir)
@property
def curr_dir_abs(self):
@@ -51,25 +50,6 @@ class GitWrapperI(object):
return path.replace('/', '\\')
return path
LONG_PATH_BUFFER_SIZE = 1024
@staticmethod
def get_long_path(path):
"""Convert short path to a full path. It is needed for Windows."""
if os.name != 'nt':
return path
buffer = create_unicode_buffer(GitWrapperI.LONG_PATH_BUFFER_SIZE)
get_long_path_name = windll.kernel32.GetLongPathNameW
result = get_long_path_name(unicode(path), buffer, GitWrapperI.LONG_PATH_BUFFER_SIZE)
if result == 0 or result > GitWrapperI.LONG_PATH_BUFFER_SIZE:
return path
return buffer.value
@staticmethod
def get_cwd():
return GitWrapperI.get_long_path(os.getcwd())
@staticmethod
def parse_porcelain_files(out):
result = []
@@ -161,11 +141,11 @@ class GitWrapper(GitWrapperI):
@staticmethod
def abs_paths_to_relative(files):
cur_dir = os.path.realpath(os.curdir)
cur_dir = System.realpath(os.curdir)
result = []
for file in files:
result.append(os.path.relpath(os.path.realpath(file), cur_dir))
result.append(os.path.relpath(System.realpath(file), cur_dir))
return result
+3 -3
View File
@@ -1,9 +1,9 @@
import os
import shutil
from dvc.path.path import Path
from dvc.exceptions import DvcException
from dvc.system import System
from dvc.utils import cached_property
@@ -100,7 +100,7 @@ class DataItem(object):
return os.path.relpath(self.cache.relative, data_file_dir)
def create_symlink(self):
os.symlink(self._symlink_file, self.data.relative)
System.symlink(self._symlink_file, self.data.relative)
def move_data_to_cache(self):
cache_dir = os.path.dirname(self.cache.relative)
@@ -108,4 +108,4 @@ class DataItem(object):
os.makedirs(cache_dir)
shutil.move(self.data.relative, self.cache.relative)
os.symlink(self._symlink_file, self.data.relative)
System.symlink(self._symlink_file, self.data.relative)
+4 -3
View File
@@ -3,13 +3,14 @@ import os
from dvc.path.data_item import DataItem, DataItemError, NotInDataDirError
from dvc.path.path import Path
from dvc.path.stated_data_item import StatedDataItem
from dvc.system import System
class PathFactory(object):
def __init__(self, git, config):
self._git = git
self._config = config
self._curr_dir_abs = os.path.realpath(os.curdir)
self._curr_dir_abs = System.realpath(os.curdir)
def path(self, relative_raw):
return Path(relative_raw, self._git)
@@ -24,9 +25,9 @@ class PathFactory(object):
if not os.path.exists(file):
raise DataItemError(u'Data file "%s" is not exist' % file)
if not os.path.islink(file):
if not System.islink(file):
raise DataItemError(u'Data file "%s" must be a symbolic link' % file)
resolved_symlink = os.path.realpath(file)
resolved_symlink = System.realpath(file)
return DataItem(file, self._git, self._config, resolved_symlink)
def to_data_items(self, files):
+2 -2
View File
@@ -1,12 +1,12 @@
import os
from dvc.git_wrapper import GitWrapperI
from dvc.system import System
class Path(object):
def __init__(self, path, git):
if not os.path.isabs(path):
pwd = GitWrapperI.get_cwd()
pwd = System.get_cwd()
path = os.path.normpath(os.path.join(pwd, path))
self._abs = path
+2 -73
View File
@@ -1,96 +1,25 @@
import os
import re
import sys
import ctypes
from dvc.config import Config, ConfigI
from dvc.exceptions import DvcException
from dvc.executor import Executor
from dvc.git_wrapper import GitWrapper
from dvc.logger import Logger
from dvc.settings import Settings
from dvc.system import System
class Runtime(object):
CONFIG = 'dvc.conf'
SYMLINC_OVERRIDE = None
REALPATH_NATIVE = None
@staticmethod
def ls_command_name():
if os.name == 'nt':
return 'dir'
return 'ls'
@staticmethod
def symlink_setup():
if os.name != 'nt':
return
Runtime._setup_windows_symlink()
os.symlink = Runtime.symlink
os.path.islink = Runtime.is_link
Runtime.REALPATH_NATIVE = os.path.realpath
os.path.realpath = Runtime.realpath
@staticmethod
def _setup_windows_symlink():
func = ctypes.windll.kernel32.CreateSymbolicLinkW
func.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
func.restype = ctypes.c_ubyte
Runtime.SYMLINC_OVERRIDE = func
@staticmethod
def is_link(path):
if not os.path.exists(path):
return False
if not os.path.isfile(path):
return False
# It is definitely not the best way to check a symlink.
code, output, _ = Executor.exec_cmd(["dir", path], shell=True)
if code != 0:
return False
return '<SYMLINK>' in output
@staticmethod
def realpath(path):
if os.name != 'nt':
return Runtime.REALPATH_NATIVE(path)
if not os.path.islink(path):
return Runtime.REALPATH_NATIVE(path)
# It is definitely not the best way to check a symlink.
code, output, _ = Executor.exec_cmd(["dir", path], shell=True)
if code != 0 or not '<SYMLINK>' in output:
return os.path.realpath(path)
groups = re.compile(r'\[\S+\]$').findall(output.strip())
if len(groups) < 1:
return Runtime.REALPATH_NATIVE(path)
resolved_link = groups[0][1:-1]
return resolved_link
@staticmethod
def symlink(source, link_name):
'''symlink(source, link_name) - DVC override for Windows
Creates a symbolic link pointing to source named link_name'''
flags = 0
if source is not None and os.path.isdir(source):
flags = 1
if Runtime.SYMLINC_OVERRIDE(link_name, source, flags) == 0:
raise ctypes.WinError()
@staticmethod
def conf_file_path(git_dir):
return os.path.realpath(os.path.join(git_dir, Runtime.CONFIG))
return System.realpath(os.path.join(git_dir, Runtime.CONFIG))
@staticmethod
def run(cmd_class, parse_config=True):
+2 -2
View File
@@ -4,7 +4,7 @@ import json
import time
from dvc.exceptions import DvcException
from dvc.git_wrapper import GitWrapperI
from dvc.system import System
class StateFileError(DvcException):
@@ -127,7 +127,7 @@ class StateFile(object):
return result
def get_dvc_path(self):
pwd = GitWrapperI.get_cwd()
pwd = System.get_cwd()
if not pwd.startswith(self.git.git_dir_abs):
raise StateFileError('the file cannot be created outside of a git repository')
+101
View File
@@ -0,0 +1,101 @@
import ctypes
import os
import re
if os.name == 'nt':
from ctypes import create_unicode_buffer, windll
from dvc.executor import Executor
class System(object):
SYMLINK_OUTPUT = '<SYMLINK>'
LONG_PATH_BUFFER_SIZE = 1024
@staticmethod
def is_unix():
return os.name != 'nt'
@staticmethod
def symlink(source, link_name):
if System.is_unix():
return os.symlink(source, link_name)
flags = 0
if source is not None and os.path.isdir(source):
flags = 1
func = ctypes.windll.kernel32.CreateSymbolicLinkW
func.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
func.restype = ctypes.c_ubyte
if func(link_name, source, flags) == 0:
raise ctypes.WinError()
@staticmethod
def islink(path):
# It is definitely not the best way to check a symlink.
if System.is_unix():
return os.path.islink(path)
if not os.path.exists(path):
return False
if not os.path.isfile(path):
return False
return System._get_symlink_string() is not None
@staticmethod
def _get_symlink_string(path):
code, output, _ = Executor.exec_cmd(["dir", path], shell=True)
if code != 0:
return False
lines = output.split('\n')
for line in lines:
if System.SYMLINK_OUTPUT in line:
return line
return None
@staticmethod
def realpath(path):
# It is definitely not the best way to check a symlink.
if System.is_unix():
return os.path.realpath(path)
output = System._get_symlink_string(path)
if output is None:
return os.path.realpath(path)
groups = re.compile(r'\[\S+\]$').findall(output.strip())
if len(groups) < 1:
return os.path.realpath(path)
resolved_link = groups[0][1:-1]
return resolved_link
@staticmethod
def ls_command_name():
if System.is_unix():
return 'ls'
return 'dir'
@staticmethod
def get_long_path(path):
"""Convert short path to a full path. It is needed for Windows."""
if System.is_unix():
return path
buffer = create_unicode_buffer(System.LONG_PATH_BUFFER_SIZE)
get_long_path_name = windll.kernel32.GetLongPathNameW
result = get_long_path_name(unicode(path), buffer, System.LONG_PATH_BUFFER_SIZE)
if result == 0 or result > System.LONG_PATH_BUFFER_SIZE:
return path
return buffer.value
@staticmethod
def get_cwd():
return System.get_long_path(os.getcwd())
+6 -5
View File
@@ -7,23 +7,24 @@ from dvc.git_wrapper import GitWrapperI
from dvc.path.data_item import DataItem
from dvc.path.factory import PathFactory
from dvc.settings import Settings
from dvc.system import System
from dvc.utils import rmtree
class BasicEnvironment(TestCase):
def init_environment(self,
test_dir=GitWrapperI.get_long_path(tempfile.mkdtemp()),
test_dir=System.get_long_path(tempfile.mkdtemp()),
curr_dir=None):
self._test_dir = os.path.realpath(test_dir)
self._test_dir = System.realpath(test_dir)
self._proj_dir = 'proj'
self._test_git_dir = os.path.join(self._test_dir, self._proj_dir)
self._old_curr_dir_abs = os.path.realpath(os.curdir)
self._old_curr_dir_abs = System.realpath(os.curdir)
if os.path.exists(self._test_dir):
rmtree(self._test_dir)
if curr_dir:
self._curr_dir = os.path.realpath(curr_dir)
self._curr_dir = System.realpath(curr_dir)
else:
self._curr_dir = self._test_git_dir
@@ -112,7 +113,7 @@ class DirHierarchyEnvironment(BasicEnvironment):
self.create_content_file(cache_result, content)
relevant_dir = self.relevant_dir(data_file)
os.symlink(os.path.join(relevant_dir, cache_result), file_result)
System.symlink(os.path.join(relevant_dir, cache_result), file_result)
else:
cache_result = None
self.create_content_file(file_result, content)
+4 -3
View File
@@ -7,15 +7,16 @@ from dvc.config import ConfigI
from dvc.executor import Executor
from dvc.path.data_item import DataItem
from dvc.path.factory import PathFactory
from dvc.git_wrapper import GitWrapper, GitWrapperI
from dvc.git_wrapper import GitWrapper
from dvc.settings import Settings
from dvc.system import System
from dvc.utils import rmtree
class RunBasicTest(TestCase):
def setUp(self):
self.test_dir = GitWrapperI.get_long_path(tempfile.mkdtemp())
self._old_curr_dir_abs = os.path.realpath(os.curdir)
self.test_dir = System.get_long_path(tempfile.mkdtemp())
self._old_curr_dir_abs = System.realpath(os.curdir)
self.tearDown()
os.mkdir(self.test_dir)
+2 -1
View File
@@ -4,6 +4,7 @@ from dvc.config import ConfigI
from dvc.git_wrapper import GitWrapperI
from dvc.path.data_item import NotInDataDirError, DataItemError, DataItem
from dvc.path.factory import PathFactory
from dvc.system import System
from tests.basic_env import BasicEnvironment
@@ -51,7 +52,7 @@ class TestPathFactory(BasicEnvironment):
fd.close()
os.chdir('data')
os.symlink(os.path.join('..', self.cache_file), 'file.txt')
System.symlink(os.path.join('..', self.cache_file), 'file.txt')
os.chdir('..')
pass
+3 -2
View File
@@ -4,12 +4,13 @@ from unittest import TestCase
from dvc.path.path import Path
from dvc.git_wrapper import GitWrapperI
from dvc.system import System
class TestDvcPathTest(TestCase):
def setUp(self):
self.curr_dir = os.path.realpath('.')
self.test_dir = os.path.realpath('/tmp/ntx_unit_test/dvc_path')
self.curr_dir = System.realpath('.')
self.test_dir = System.realpath('/tmp/ntx_unit_test/dvc_path')
self.tearDown()
os.makedirs(os.path.join(self.test_dir, 'data'))
os.makedirs(os.path.join(self.test_dir, 'code', 'lib'))
+5 -6
View File
@@ -3,14 +3,13 @@ import shutil
import tempfile
from unittest import TestCase
from dvc import Runtime
from dvc.executor import Executor, ExecutorError
from dvc.git_wrapper import GitWrapperI
from dvc.system import System
class TestExecutor(TestCase):
def setUp(self):
self.test_dir = GitWrapperI.get_long_path(tempfile.mkdtemp())
self.test_dir = System.get_long_path(tempfile.mkdtemp())
self.file1 = 'file1.txt'
fd1 = open(os.path.join(self.test_dir, self.file1), 'w+')
@@ -26,14 +25,14 @@ class TestExecutor(TestCase):
shutil.rmtree(self.test_dir)
def test_suppress_output(self):
output = Executor.exec_cmd_only_success([Runtime.ls_command_name(), self.test_dir],
output = Executor.exec_cmd_only_success([System.ls_command_name(), self.test_dir],
shell=True,
cwd=self.test_dir)
output_set = set(output.split())
self.assertEqual(output_set, {self.file1, self.file2})
def test_output_to_std_console(self):
output = Executor.exec_cmd_only_success([Runtime.ls_command_name(), self.test_dir],
output = Executor.exec_cmd_only_success([System.ls_command_name(), self.test_dir],
'-',
'-',
shell=True)
@@ -42,7 +41,7 @@ class TestExecutor(TestCase):
def test_custom_file_outputs(self):
stdout_file = os.path.join(self.test_dir, 'stdout.txt')
stderr_file = os.path.join(self.test_dir, 'stderr.txt')
output = Executor.exec_cmd_only_success([Runtime.ls_command_name(), self.test_dir],
output = Executor.exec_cmd_only_success([System.ls_command_name(), self.test_dir],
stdout_file,
stderr_file,
shell=True,
+4 -3
View File
@@ -9,12 +9,13 @@ from dvc.path.factory import PathFactory
from dvc.git_wrapper import GitWrapperI
from dvc.repository_change import RepositoryChange
from dvc.settings import Settings
from dvc.system import System
class BasicTestRepositoryChange(TestCase):
def setUp(self):
self.test_dir = GitWrapperI.get_long_path(tempfile.mkdtemp())
self._old_curr_dir_abs = os.path.realpath(os.curdir)
self.test_dir = System.get_long_path(tempfile.mkdtemp())
self._old_curr_dir_abs = System.realpath(os.curdir)
self.tearDown()
os.mkdir(self.test_dir)
@@ -106,5 +107,5 @@ class TestRepositoryChangeExternallyCreated(BasicTestRepositoryChange):
None,
shell=True)
self.assertEqual([os.path.realpath(not_in_data_dir_file)],
self.assertEqual([System.realpath(not_in_data_dir_file)],
change.externally_created_files)