def test_from_file_path_default_packages_root(self):
     self.assertEqual(
         ResourcePath.from_file_path(
             Path(sublime.executable_path()).parent / 'Packages'
         ),
         ResourcePath("Packages")
     )
    def test_copytree_exists(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package")
            destination = Path(directory) / 'tree'
            destination.mkdir()

            helloworld_file = destination / 'helloworld.txt'

            with open(str(helloworld_file), 'w') as file:
                file.write("Nothing to see here.\n")

            source.copytree(destination, exist_ok=True)

            self.assertEqual(
                {
                    path.relative_to(destination).parts
                    for path in destination.rglob('*') if path.is_file()
                }, {path.relative_to(source)
                    for path in source.rglob('*')})

            with open(str(helloworld_file)) as file:
                helloworld_contents = file.read()

            self.assertEqual(helloworld_contents,
                             (source / 'helloworld.txt').read_text())
 def test_from_file_path_installed_packages(self):
     self.assertEqual(
         ResourcePath.from_file_path(
             Path(sublime.installed_packages_path(), 'test_package.sublime-package', 'foo.py')
         ),
         ResourcePath("Packages/test_package/foo.py")
     )
 def test_relative_to(self):
     self.assertEqual(
         ResourcePath("Packages/Foo/baz/bar.py").relative_to(
             ResourcePath("Packages/Foo")
         ),
         ('baz', 'bar.py')
     )
 def test_relative_to_same(self):
     self.assertEqual(
         ResourcePath("Packages/Foo").relative_to(
             ResourcePath("Packages/Foo")
         ),
         ()
     )
    def setUp(self):
        shutil.copytree(
            src=str(ResourcePath("Packages/sublime_lib/tests/test_package").file_path()),
            dst=str(ResourcePath("Packages/test_package").file_path()),
        )

        yield ResourcePath("Packages/test_package/.test_package_exists").exists
    def _copy_to_cache(self):
        src_path = 'Packages/{}/{}/'.format(self._package_name,
                                            self._server_directory)
        dst_path = 'Cache/{}/{}/'.format(self._package_name,
                                         self._server_directory)
        cache_server_path = os.path.join(self._package_cache_path,
                                         self._server_directory)

        if os.path.isdir(cache_server_path):
            # Server already in cache. Check if version has changed and if so, delete existing copy in cache.
            try:
                src_package_json = ResourcePath(src_path,
                                                'package.json').read_text()
                dst_package_json = ResourcePath(dst_path,
                                                'package.json').read_text()

                if src_package_json != dst_package_json:
                    shutil.rmtree(cache_server_path)
            except FileNotFoundError:
                shutil.rmtree(cache_server_path)

        if not os.path.isdir(cache_server_path):
            # create cache folder
            ResourcePath(src_path).copytree(cache_server_path, exist_ok=True)

        self._install_dependencies(cache_server_path)
 def test_parents(self):
     self.assertEqual(
         ResourcePath("Packages/Foo/bar.py").parents,
         (
             ResourcePath("Packages/Foo"),
             ResourcePath("Packages")
         )
     )
 def test_glob(self):
     self.assertEqual(
         ResourcePath("Packages/test_package").glob('*.txt'),
         [
             ResourcePath("Packages/test_package/helloworld.txt"),
             ResourcePath("Packages/test_package/UTF-8-test.txt"),
         ]
     )
 def test_children(self):
     self.assertEqual(
         ResourcePath("Packages/test_package").children(), [
             ResourcePath("Packages/test_package/.test_package_exists"),
             ResourcePath("Packages/test_package/helloworld.txt"),
             ResourcePath("Packages/test_package/UTF-8-test.txt"),
             ResourcePath("Packages/test_package/directory"),
         ])
 def test_rglob(self):
     self.assertEqual(
         ResourcePath("Packages/test_package").rglob('*.txt'), [
             ResourcePath("Packages/test_package/helloworld.txt"),
             ResourcePath("Packages/test_package/UTF-8-test.txt"),
             ResourcePath(
                 "Packages/test_package/directory/goodbyeworld.txt"),
         ])
 def test_glob_resources(self):
     self.assertEqual(
         ResourcePath.glob_resources("Packages/test_package/*.txt"),
         [
             ResourcePath("Packages/test_package/helloworld.txt"),
             ResourcePath("Packages/test_package/UTF-8-test.txt"),
         ]
     )
    def test_copytree_exists_error(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package")
            destination = Path(directory) / 'tree'
            destination.mkdir()

            with self.assertRaises(FileExistsError):
                source.copytree(destination)
Beispiel #14
0
 def get_scheme_path(view, setting_name):
     # Be lazy here and don't consider invalid values
     scheme_setting = view.settings().get(setting_name, DEFAULT_CS)
     if scheme_setting == 'auto':
         return 'auto'
     elif "/" not in scheme_setting:
         return ResourcePath.glob_resources(scheme_setting)[0]
     else:
         return ResourcePath(scheme_setting)
 def test_from_file_path_default_packages(self):
     self.assertEqual(
         ResourcePath.from_file_path(
             Path(sublime.executable_path()).parent.joinpath(
                 'Packages', 'test_package.sublime-package', 'foo.py'
             )
         ),
         ResourcePath("Packages/test_package/foo.py")
     )
    def test_copy_directory_error(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package/helloworld.txt")
            destination = Path(directory) / 'helloworld.txt'

            destination.mkdir()

            with self.assertRaises(IsADirectoryError):
                source.copy(destination)

            self.assertTrue(destination.is_dir())
    def test_copy_existing_error(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package/helloworld.txt")
            destination = Path(directory) / 'helloworld.txt'

            text = "Nothing to see here.\n"
            with open(str(destination), 'w') as file:
                file.write(text)

            with self.assertRaises(FileExistsError):
                source.copy(destination, False)
Beispiel #18
0
    def test_temporary_package_name(self):
        expected_resource_path = ResourcePath('Packages/TemporaryPackageTest')
        expected_file_path = expected_resource_path.file_path()

        name = 'TemporaryPackageTest'
        with TemporaryPackage(name) as path:
            self.assertEquals(path.name, name)
            self.assertEquals(path, expected_resource_path)
            self.assertTrue(expected_file_path.is_dir())

        self.assertFalse(expected_file_path.exists())
Beispiel #19
0
def remove_file_if_empty():
    path = ResourcePath("Packages/User/XML.sublime-settings").file_path()
    try:
        with path.open() as f:
            data = sublime.decode_value(f.read())
    except (FileNotFoundError, ValueError):
        pass
    else:
        if not data or len(
                data) == 1 and 'extensions' in data and not data['extensions']:
            path.unlink()
            print("[PackageDev] Removed now-empty XML.sublime-settings")
    def test_copy_text(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package/helloworld.txt")
            destination = Path(directory) / 'helloworld.txt'

            source.copy(destination)

            self.assertTrue(destination.is_file())

            with open(str(destination), 'r') as file:
                text = file.read()

            self.assertEqual(text, source.read_text())
    def test_copy_binary(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package/UTF-8-test.txt")
            destination = Path(directory) / 'UTF-8-test.txt'

            source.copy(destination)

            self.assertTrue(destination.is_file())

            with open(str(destination), 'rb') as file:
                data = file.read()

            self.assertEqual(data, source.read_bytes())
    def test_copytree(self):
        with tempfile.TemporaryDirectory() as directory:
            source = ResourcePath("Packages/test_package")
            destination = Path(directory) / 'tree'

            source.copytree(destination)

            self.assertEqual(
                {
                    path.relative_to(destination).parts
                    for path in destination.rglob('*') if path.is_file()
                }, {path.relative_to(source)
                    for path in source.rglob('*')})
Beispiel #23
0
class TemporaryPackage():
    def __init__(
        self,
        name: Optional[str] = None,
        *,
        prefix: Optional[str] = None,
        suffix: Optional[str] = None,
        copy_from: Optional[str] = None,
        wrap_ignore: bool = True
    ) -> None:
        if name is None:
            self._name = '{prefix}{token}{suffix}'.format(
                prefix=prefix or '',
                token=random_token(),
                suffix=suffix or '',
            )
        elif prefix is not None or suffix is not None:
            raise ValueError("Argument `name` is incompatible with `prefix` and `suffix`.")
        else:
            self._name = name

        self.copy_from = copy_from
        self.wrap_ignore = wrap_ignore

        self.path = ResourcePath('Packages', self._name)

    def __enter__(self) -> ResourcePath:
        self.init()
        return self.path

    def __exit__(self, exc_type: type, exc_value: Exception, traceback: TracebackType) -> None:
        self.cleanup()

    def _ignore(self) -> ContextManager:
        ret = ExitStack()
        if self.wrap_ignore:
            ret.enter_context(ignore_package(self._name))
        return ret

    def init(self) -> None:
        with self._ignore():
            if self.copy_from is None:
                mkdir(str(self.path.file_path()))
            else:
                ResourcePath(self.copy_from).copytree(self.path.file_path())

    def cleanup(self) -> None:
        with self._ignore():
            rmtree(str(self.path.file_path()))
Beispiel #24
0
 def _load_package_schemas(self) -> List[Any]:
     global_preferences_schemas = []
     resources = ResourcePath.glob_resources('sublime-package.json')
     for resource in resources:
         schema = self._parse_schema(resource)
         if not schema:
             continue
         settings = schema.get('contributions').get('settings')
         for s in settings:
             i = len(self._schema_uri_to_content)
             file_patterns = s.get('file_patterns')
             schema_content = s.get('schema')
             uri = schema_content.get(
                 '$id') or 'sublime://settings/{}'.format(i)
             self._schema_uri_to_content[uri] = sublime.encode_value(
                 schema_content, pretty=False)
             self._register_schemas([{
                 'fileMatch': file_patterns,
                 'uri': uri
             }])
             if file_patterns:
                 for pattern in file_patterns:
                     if pattern == '/Preferences.sublime-settings':
                         global_preferences_schemas.append(schema_content)
     return global_preferences_schemas
    def setUp(self):
        self.temp = TemporaryPackage(
            'test_package',
            ResourcePath("Packages/sublime_lib/tests/test_package"))
        self.temp.create()

        yield self.temp.exists
Beispiel #26
0
 def needs_installation(self) -> bool:
     if os.path.exists(self.server_exe()) and os.path.exists(
             self.pip_exe()):
         if not os.path.exists(self.python_version()):
             return True
         with open(self.python_version(), 'r') as f:
             if f.readline().strip() != self.run(self.python_exe(),
                                                 '--version').strip():
                 return True
         installed_requirements = parse_requirements(
             self.run(self.pip_exe(), 'freeze'))
         requirements = parse_requirements(
             ResourcePath(self._requirements_path).read_text())
         for name, version in requirements.items():
             if name not in installed_requirements:
                 # Has new requirement
                 return True
             if not version:
                 continue
             installed_version = installed_requirements.get(name)
             if version != installed_version:
                 return True
         self._status = ServerStatus.READY
         return False
     return True
Beispiel #27
0
def get_extensions(path):
    arguments = (yield).context
    ret = []

    extensions = list(list_extensions(ResourcePath(path)))

    for extension in extensions:
        metadata, extension_value = extension

        options = arguments.get(metadata['name'])

        if options is not None and options is not False:
            constructor = get_loader(
                macros_root=metadata['macros_root']).constructor

            if 'legacy_argument' in metadata:
                options = {metadata['legacy_argument']: options}
            elif not isinstance(options, dict):
                default_argument = metadata.get('default_argument')
                if default_argument:
                    options = {default_argument: options}
                else:
                    options = {}

            with constructor.set_context(**options):
                result = constructor.construct_document(extension_value)
                ret.append(result)

    return ret
Beispiel #28
0
    def run(self, **kwargs):

        # plugin settings
        self.package_dir = ResourcePath.from_file_path(__file__).parent
        self.plugin_name = 'C++ Classhelper'
        self.template_dir_name = 'templates'
        # self.template_dir = "{}/{}/".format(self.package_dir, self.template_dir_name)
        self.template_dir = self.package_dir / self.template_dir_name

        # global settings
        self.settings = sublime.load_settings(
            "C++ Classhelper.sublime-settings")
        self.vars = self.window.extract_variables()
        self.view = self.window.active_view()

        self.header_file_extension = self.settings.get('header_file_extension')

        # directory where files will be created
        print(self.vars)
        if not "file_path" in self.vars:
            self.create_directory = self.vars['folder']
        else:
            self.create_directory = self.vars['file_path']

        # get folder from sidebar
        if "paths" in kwargs:
            self.create_directory = kwargs['paths'][0]

        # user enter a class name to create the class
        self.window.show_input_panel("Enter class name: ", "",
                                     self.create_class, None, None)
def plugin_loaded(reload=False):

    try:
        global settings
        settings = sublime.load_settings('LSL.sublime-settings')
        settings.clear_on_change('reload')
        settings.add_on_change('reload', lambda: plugin_loaded(reload=True))
        global INDENT_STYLE_FILE
        INDENT_STYLE_FILE = ResourcePath(RESPATH_INDENT_STYLE).file_path()
        if not ResourcePath(RESPATH_INDENT_STYLE).exists():
            set_indent_style('allman')
    except Exception as e:
        print(e)

    if reload:
        status_msg('Reloaded settings on change.')
Beispiel #30
0
def get_extensions(path):
    arguments = (yield).context
    ret = []

    extensions = list(list_extensions(ResourcePath(path)))

    # Hack hacky hack to make sure that JSX is after TypeScript
    extensions.sort(key=lambda pair: pair[0]['name'] == 'jsx')

    for extension in extensions:
        metadata, extension_value = extension

        options = arguments.get(metadata['name'])

        if options is not None and options is not False:
            constructor = get_loader(
                macros_root=metadata['macros_root']).constructor

            if 'legacy_argument' in metadata:
                options = {metadata['legacy_argument']: options}
            elif not isinstance(options, dict):
                default_argument = metadata.get('default_argument')
                if default_argument:
                    options = {default_argument: options}
                else:
                    options = {}

            with constructor.set_context(**options):
                result = constructor.construct_document(extension_value)
                result = convert_extension(result)
                ret.append(result)

    return ret