Python os.path.normcase() Examples

The following are 30 code examples of os.path.normcase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os.path , or try the search function .
Example #1
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_debug_code(code):
    if not code or not code.co_filename:
        return False

    filename = path.normcase(code.co_filename)
    if not DEBUG_STDLIB:
        for prefix in PREFIXES:
            if prefix != '' and filename.startswith(prefix):
                return False

    for dont_debug_file in DONT_DEBUG:
        if is_same_py_file(filename, dont_debug_file):
            return False

    if is_file_in_zip(filename):
        # file in inside an egg or zip, so we can't debug it
        return False

    return True 
Example #2
Source File: test_cli.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_set_env_path_with_node_path_success(self):
        tmpdir, bin_dir, mgr_bin = self.fake_mgr_bin()
        other_dir = mkdtemp(self)
        # default constructor
        driver = cli.PackageManagerDriver(
            pkg_manager_bin='mgr', working_dir=other_dir)
        # the which_with_node_modules will not work immeidately in this
        # case
        self.assertIsNone(driver.which_with_node_modules())
        self.assertIsNone(driver.env_path)
        # using NODE_PATH set to a valid node_modules
        driver.node_path = join(tmpdir, 'node_modules')
        # this should work now.
        self.assertEqual(
            normcase(driver.which_with_node_modules()), normcase(mgr_bin))
        self.assertTrue(driver._set_env_path_with_node_modules())
        self.assertEqual(driver.env_path, bin_dir)
        # should still result in the same thing.
        self.assertTrue(driver._set_env_path_with_node_modules())
        self.assertEqual(driver.env_path, bin_dir) 
Example #3
Source File: test_indexer.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_missing_distribution(self):
        d_egg_root = join(mkdtemp(self), 'dummyns')
        make_dummy_dist(self, ((
            'namespace_packages.txt',
            'not_ns\n',
        ), (
            'entry_points.txt',
            '[dummyns]\n'
            'dummyns = dummyns:attr\n',
        ),), 'dummyns', '2.0', working_dir=d_egg_root)
        working_set = pkg_resources.WorkingSet([
            d_egg_root,
            self.ds_egg_root,
        ])
        dummyns_ep = next(working_set.iter_entry_points('dummyns'))
        with pretty_logging(stream=StringIO()) as fd:
            p = indexer.resource_filename_mod_entry_point(
                'dummyns', dummyns_ep)
        # not stubbed working_set, so this is derived using fallback
        # value from the sys.modules['dummyns'] location
        self.assertEqual(normcase(p), normcase(self.dummyns_path))
        self.assertIn("distribution 'dummyns 2.0' not found", fd.getvalue()) 
Example #4
Source File: _os.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def safe_join(base, *paths):
    """
    Joins one or more path components to the base path component intelligently.
    Returns a normalized, absolute version of the final path.

    The final path must be located inside of the base path component (otherwise
    a ValueError is raised).
    """
    # We need to use normcase to ensure we don't false-negative on case
    # insensitive operating systems (like Windows).
    base = force_unicode(base)
    paths = [force_unicode(p) for p in paths]
    final_path = normcase(abspathu(join(base, *paths)))
    base_path = normcase(abspathu(base))
    base_path_len = len(base_path)
    # Ensure final_path starts with base_path and that the next character after
    # the final path is os.sep (or nothing, in which case final_path must be
    # equal to base_path).
    if not final_path.startswith(base_path) or final_path[base_path_len:base_path_len+1] not in ('', sep):
        raise ValueError('the joined path is located outside of the base path'
                         ' component')
    return final_path 
Example #5
Source File: path.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False 
Example #6
Source File: _os.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def safe_join(base, *paths):
    """
    Joins one or more path components to the base path component intelligently.
    Returns a normalized, absolute version of the final path.

    The final path must be located inside of the base path component (otherwise
    a ValueError is raised).
    """
    base = force_text(base)
    paths = [force_text(p) for p in paths]
    final_path = abspathu(join(base, *paths))
    base_path = abspathu(base)
    # Ensure final_path starts with base_path (using normcase to ensure we
    # don't false-negative on case insensitive operating systems like Windows),
    # further, one of the following conditions must be true:
    #  a) The next character is the path separator (to prevent conditions like
    #     safe_join("/dir", "/../d"))
    #  b) The final path must be the same as the base path.
    #  c) The base path must be the most root path (meaning either "/" or "C:\\")
    if (not normcase(final_path).startswith(normcase(base_path + sep)) and
        normcase(final_path) != normcase(base_path) and
        dirname(normcase(base_path)) != normcase(base_path)):
        raise ValueError('The joined path (%s) is located outside of the base '
                         'path component (%s)' % (final_path, base_path))
    return final_path 
Example #7
Source File: path.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False 
Example #8
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_debug_code(code):
    if not code or not code.co_filename:
        return False

    filename = path.normcase(code.co_filename)
    if not DEBUG_STDLIB:
        for prefix in PREFIXES:
            if prefix != '' and filename.startswith(prefix):
                return False

    for dont_debug_file in DONT_DEBUG:
        if is_same_py_file(filename, dont_debug_file):
            return False

    if is_file_in_zip(filename):
        # file in inside an egg or zip, so we can't debug it
        return False

    return True 
Example #9
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_block_on_frame(self, frame):
        if not should_debug_code(frame.f_code):
            return False
        # It is still possible that we're somewhere in standard library code, but that code was invoked by our
        # internal debugger machinery (e.g. socket.sendall or text encoding while tee'ing print output to VS).
        # We don't want to block on any of that, either, so walk the stack and see if we hit debugger frames
        # at some point below the non-debugger ones.
        while frame is not None:
            # There is usually going to be a debugger frame at the very bottom of the stack - the one that
            # invoked user code on this thread when starting debugging. If we reached that, then everything
            # above is user code, so we know that we do want to block here.
            if frame.f_code in DEBUG_ENTRYPOINTS:
                break
            # Otherwise, check if it's some other debugger code.
            filename = path.normcase(frame.f_code.co_filename)
            is_debugger_frame = False
            for debugger_file in DONT_DEBUG:
                if is_same_py_file(filename, debugger_file):
                    # If it is, then the frames above it on the stack that we have just walked through
                    # were for debugger internal purposes, and we do not want to block here.
                    return False
            frame = frame.f_back
        return True 
Example #10
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_block_on_frame(self, frame):
        if not should_debug_code(frame.f_code):
            return False
        # It is still possible that we're somewhere in standard library code, but that code was invoked by our
        # internal debugger machinery (e.g. socket.sendall or text encoding while tee'ing print output to VS).
        # We don't want to block on any of that, either, so walk the stack and see if we hit debugger frames
        # at some point below the non-debugger ones.
        while frame is not None:
            # There is usually going to be a debugger frame at the very bottom of the stack - the one that
            # invoked user code on this thread when starting debugging. If we reached that, then everything
            # above is user code, so we know that we do want to block here.
            if frame.f_code in DEBUG_ENTRYPOINTS:
                break
            # Otherwise, check if it's some other debugger code.
            filename = path.normcase(frame.f_code.co_filename)
            is_debugger_frame = False
            for debugger_file in DONT_DEBUG:
                if is_same_py_file(filename, debugger_file):
                    # If it is, then the frames above it on the stack that we have just walked through
                    # were for debugger internal purposes, and we do not want to block here.
                    return False
            frame = frame.f_back
        return True 
Example #11
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def breakpoint_path_match(vs_path, local_path):
    vs_path_norm = path.normcase(vs_path)
    local_path_norm = path.normcase(local_path)
    if local_path_to_vs_path.get(local_path_norm) == vs_path_norm:
        return True
    
    # Walk the local filesystem from local_path up, matching agains win_path component by component,
    # and stop when we no longer see an __init__.py. This should give a reasonably close approximation
    # of matching the package name.
    while True:
        local_path, local_name = path.split(local_path)
        vs_path, vs_name = ntpath.split(vs_path)
        # Match the last component in the path. If one or both components are unavailable, then
        # we have reached the root on the corresponding path without successfully matching.
        if not local_name or not vs_name or path.normcase(local_name) != path.normcase(vs_name):
            return False
        # If we have an __init__.py, this module was inside the package, and we still need to match
        # thatpackage, so walk up one level and keep matching. Otherwise, we've walked as far as we
        # needed to, and matched all names on our way, so this is a match.
        if not path.exists(path.join(local_path, '__init__.py')):
            break
    
    local_path_to_vs_path[local_path_norm] = vs_path_norm
    return True 
Example #12
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #13
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_debug_code(code):
    if not code or not code.co_filename:
        return False

    filename = path.normcase(code.co_filename)
    if not DEBUG_STDLIB:
        for prefix in PREFIXES:
            if prefix != '' and filename.startswith(prefix):
                return False

    for dont_debug_file in DONT_DEBUG:
        if is_same_py_file(filename, dont_debug_file):
            return False

    if is_file_in_zip(filename):
        # file in inside an egg or zip, so we can't debug it
        return False

    return True 
Example #14
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_debug_code(code):
    if not code or not code.co_filename:
        return False

    filename = path.normcase(code.co_filename)
    if not DEBUG_STDLIB:
        for prefix in PREFIXES:
            if prefix != '' and filename.startswith(prefix):
                return False

    for dont_debug_file in DONT_DEBUG:
        if is_same_py_file(filename, dont_debug_file):
            return False

    if is_file_in_zip(filename):
        # file in inside an egg or zip, so we can't debug it
        return False

    return True 
Example #15
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def breakpoint_path_match(vs_path, local_path):
    vs_path_norm = path.normcase(vs_path)
    local_path_norm = path.normcase(local_path)
    if local_path_to_vs_path.get(local_path_norm) == vs_path_norm:
        return True
    
    # Walk the local filesystem from local_path up, matching agains win_path component by component,
    # and stop when we no longer see an __init__.py. This should give a reasonably close approximation
    # of matching the package name.
    while True:
        local_path, local_name = path.split(local_path)
        vs_path, vs_name = ntpath.split(vs_path)
        # Match the last component in the path. If one or both components are unavailable, then
        # we have reached the root on the corresponding path without successfully matching.
        if not local_name or not vs_name or path.normcase(local_name) != path.normcase(vs_name):
            return False
        # If we have an __init__.py, this module was inside the package, and we still need to match
        # thatpackage, so walk up one level and keep matching. Otherwise, we've walked as far as we
        # needed to, and matched all names on our way, so this is a match.
        if not path.exists(path.join(local_path, '__init__.py')):
            break
    
    local_path_to_vs_path[local_path_norm] = vs_path_norm
    return True 
Example #16
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_block_on_frame(self, frame):
        if not should_debug_code(frame.f_code):
            return False
        # It is still possible that we're somewhere in standard library code, but that code was invoked by our
        # internal debugger machinery (e.g. socket.sendall or text encoding while tee'ing print output to VS).
        # We don't want to block on any of that, either, so walk the stack and see if we hit debugger frames
        # at some point below the non-debugger ones.
        while frame is not None:
            # There is usually going to be a debugger frame at the very bottom of the stack - the one that
            # invoked user code on this thread when starting debugging. If we reached that, then everything
            # above is user code, so we know that we do want to block here.
            if frame.f_code in DEBUG_ENTRYPOINTS:
                break
            # Otherwise, check if it's some other debugger code.
            filename = path.normcase(frame.f_code.co_filename)
            is_debugger_frame = False
            for debugger_file in DONT_DEBUG:
                if is_same_py_file(filename, debugger_file):
                    # If it is, then the frames above it on the stack that we have just walked through
                    # were for debugger internal purposes, and we do not want to block here.
                    return False
            frame = frame.f_back
        return True 
Example #17
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_exception(exc_type, exc_value, exc_tb):
    # remove debugger frames from the top and bottom of the traceback
    tb = traceback.extract_tb(exc_tb)
    for i in [0, -1]:
        while tb:
            frame_file = path.normcase(tb[i][0])
            if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG):
                break
            del tb[i]

    # print the traceback
    if tb:
        print('Traceback (most recent call last):')
        for out in traceback.format_list(tb):
            sys.stderr.write(out)
    
    # print the exception
    for out in traceback.format_exception_only(exc_type, exc_value):
        sys.stdout.write(out) 
Example #18
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_block_on_frame(self, frame):
        if not should_debug_code(frame.f_code):
            return False
        # It is still possible that we're somewhere in standard library code, but that code was invoked by our
        # internal debugger machinery (e.g. socket.sendall or text encoding while tee'ing print output to VS).
        # We don't want to block on any of that, either, so walk the stack and see if we hit debugger frames
        # at some point below the non-debugger ones.
        while frame is not None:
            # There is usually going to be a debugger frame at the very bottom of the stack - the one that
            # invoked user code on this thread when starting debugging. If we reached that, then everything
            # above is user code, so we know that we do want to block here.
            if frame.f_code in DEBUG_ENTRYPOINTS:
                break
            # Otherwise, check if it's some other debugger code.
            filename = path.normcase(frame.f_code.co_filename)
            is_debugger_frame = False
            for debugger_file in DONT_DEBUG:
                if is_same_py_file(filename, debugger_file):
                    # If it is, then the frames above it on the stack that we have just walked through
                    # were for debugger internal purposes, and we do not want to block here.
                    return False
            frame = frame.f_back
        return True 
Example #19
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_getsourcefile(self):
        self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile)
        self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile)
        fn = "_non_existing_filename_used_for_sourcefile_test.py"
        co = compile("None", fn, "exec")
        self.assertEqual(inspect.getsourcefile(co), None)
        linecache.cache[co.co_filename] = (1, None, "None", co.co_filename)
        try:
            self.assertEqual(normcase(inspect.getsourcefile(co)), fn)
        finally:
            del linecache.cache[co.co_filename] 
Example #20
Source File: FileProxy.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, filename, workspace=None, contents=''):
        """
        Initialize the FileProxy instance with the passed
        parameters. A FileProxy instance always starts at
        a fresh state with a negative version indicating
        that no updating operation has been performed on it.

        :param filename:
            The name of the file to create a FileProxy of.
            The filename is internally normcased.
        :param workspace:
            The workspace/project this file belongs to.
            Can be None.
        :param contents:
            The contents of the file to initialize the
            instance with. Integrity of the content or the
            sync state is never checked during initialization.
        """
        logging.debug('File proxy for {} created'.format(filename))

        # The file may not exist yet, hence there is no
        # reliable way of knowing if it is a file on the
        # disk or a directory.
        if not path.isabs(filename) or filename.endswith(path.sep):
            raise ValueError('expecting absolute filename')

        self._version = -1
        self._contents = contents
        self._filename = path.normcase(filename)
        self._workspace = workspace and path.normcase(workspace) 
Example #21
Source File: _os.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def safe_join(base, *paths):
    """
    Join one or more path components to the base path component intelligently.
    Return a normalized, absolute version of the final path.

    Raise ValueError if the final path isn't located inside of the base path
    component.
    """
    base = force_text(base)
    paths = [force_text(p) for p in paths]
    final_path = abspath(join(base, *paths))
    base_path = abspath(base)
    # Ensure final_path starts with base_path (using normcase to ensure we
    # don't false-negative on case insensitive operating systems like Windows),
    # further, one of the following conditions must be true:
    #  a) The next character is the path separator (to prevent conditions like
    #     safe_join("/dir", "/../d"))
    #  b) The final path must be the same as the base path.
    #  c) The base path must be the most root path (meaning either "/" or "C:\\")
    if (not normcase(final_path).startswith(normcase(base_path + sep)) and
            normcase(final_path) != normcase(base_path) and
            dirname(normcase(base_path)) != normcase(base_path)):
        raise SuspiciousFileOperation(
            'The joined path ({}) is located outside of the base path '
            'component ({})'.format(final_path, base_path))
    return final_path 
Example #22
Source File: FileProxy.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def remove(self, filename):
        """
        Remove the proxy associated with a file from the
        proxy map.

        :param filename:
            The name of the file to remove the proxy
            associated with.
        """
        filename = path.normcase(filename)
        if self.get(filename):
            del self._map[filename] 
Example #23
Source File: FileProxy.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, filename):
        """
        :param filename:
            The name of file to get the associated proxy instance.
        :return:
            A file proxy instance or None if not available.
        """
        filename = path.normcase(filename)
        return self._map.get(filename) 
Example #24
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def should_send_frame(frame):
    return (frame is not None and
            frame.f_code not in DEBUG_ENTRYPOINTS and
            path.normcase(frame.f_code.co_filename) not in DONT_DEBUG) 
Example #25
Source File: FileProxy.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def resolve(self, filename, workspace=None, hard_sync=True, binary=False):
        """
        Resolve tries to find an available proxy or creates one
        if there is no available proxy for the said file.

        :param filename:
            The filename to search for in the map or to create
            a proxy instance using.
        :param workspace:
            Used in case the lookup fails and a new instance is
            being initialized.
        :hard_sync:
            Boolean flag indicating if the file should be initialized
            from the file on disk or fail otherwise.
        :return:
            Returns a proxy instance or raises associated exceptions.
        """
        filename = path.normcase(filename)

        proxy = self.get(filename)
        if proxy is not None:
            return proxy

        try:
            proxy = FileProxy.from_file(filename, workspace, binary=binary)
        except (OSError, ValueError) as ex:
            if hard_sync:
                raise ex

            # Could raise a ValueError
            proxy = FileProxy(filename, workspace)
            self.add(proxy)

        return proxy 
Example #26
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_to_repl_backend_using_socket(self, sock):
        DONT_DEBUG.append(path.normcase(_vspr.__file__))
        self.repl_backend = _vspr.DebugReplBackend(self)
        self.repl_backend.connect_from_debugger_using_socket(sock)
        self.repl_backend.execution_loop() 
Example #27
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_to_repl_backend(self, port_num):
        DONT_DEBUG.append(path.normcase(_vspr.__file__))
        self.repl_backend = _vspr.DebugReplBackend(self)
        self.repl_backend.connect_from_debugger(port_num)
        self.repl_backend.execution_loop() 
Example #28
Source File: _imports.py    From pyce with Apache License 2.0 5 votes vote down vote up
def get_code(self, fullname: str) -> Any:
        """
        Decrypt, and interpret as Python bytecode into a module return.

        Args:
            fullname: The name of the module to decrypt and compile

        Returns:
            Compiled bytecode
        """
        path = self.get_filename(fullname)
        data = self.get_data(path)

        # It is important to normalize path case for platforms like Windows
        data = decrypt(data, PYCEPathFinder.KEYS[normcase(relpath(path))])

        # Call _classify_pyc to do basic validation of the pyc but ignore the
        # result. There's no source to check against.
        exc_details = {
            'name': fullname,
            'path': path,
        }
        _classify_pyc(data, fullname, exc_details)

        return _compile_bytecode(
            memoryview(data)[16:],
            name=fullname,
            bytecode_path=path,
        ) 
Example #29
Source File: pytest_config.py    From odl with Mozilla Public License 2.0 5 votes vote down vote up
def pytest_ignore_collect(path, config):
    normalized = os.path.normcase(str(path))
    return any(normalized.startswith(ignored) for ignored in collect_ignore)


# --- Reusable fixtures --- #

# NOTE: All global fixtures need to be prefixed with `odl_` to make them
# non-conflicting with other packages' fixture names, since these fixtures
# are exposed globally across packages by setuptools.

# Simple ones, use helper 
Example #30
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def revise(filename, *args):
    return (normcase(filename),) + args