def _naive_relative_to(path: PosixPath, root: PosixPath) -> PurePosixPath: """ Compute relative PurePosixPath, result may include '..' parts. Both arguments must be absolute PurePosixPath's and lack '..' parts. Possibility of symlinks is ignored, i. e. arguments are interpreted as resolved paths. """ if not path.is_absolute(): raise ValueError(path) if not root.is_absolute(): raise ValueError(root) if '..' in path.parts: raise ValueError(path) if '..' in root.parts: raise ValueError(root) upstairs = 0 while root not in path.parents: parent = root.parent assert parent != root root = parent upstairs += 1 return PurePosixPath( * (('..',) * upstairs), path.relative_to(root) )
def filelist_from_patterns(patterns, ignore=None, base='.', sizesort=False): base = Path(base or '.').expanduser() filenames = set() for pattern in patterns or []: path = base / pattern if path.is_file(): filenames.add(path) continue if path.is_dir(): path += '/*' parts = path.parts[1:] if path.is_absolute() else path.parts pattern = str(Path("").joinpath(*parts)) filenames.update( (p for p in Path(path.root).glob(pattern) if not p.is_dir())) filenames = list(filenames) def excluded(path): if any(path.match(ex) for ex in ignore): return True for part in path.parts: if any(Path(part).match(ex) for ex in ignore): return True if ignore: filenames = [path for path in filenames if not excluded(path)] if sizesort: filenames.sort(key=lambda f: f.stat().st_size) return filenames
def encode_path(path: fs.Path) -> str: if not isinstance(path, fs.Path): raise TypeError if path.is_absolute() or not path.is_normalized(): raise ValueError encoded_path = path.as_string() if encoded_path[-1:] != '/': encoded_path = encoded_path + '/' # to enable efficient search for path prefixes in SQL if encoded_path[:2] == './': encoded_path = encoded_path[2:] return encoded_path
def __call__(self, ctx) -> str: from pathlib import Path path = Path(self._path) if not path.is_absolute(): path = Path(ctx._pwd) / path path = path.absolute() if not path.exists(): path.mkdir(parents=True, exist_ok=True) elif not path.is_dir(): raise ConfigurationError("'%s' is not a directory" % self._path) return str(path)
def lookForFile(path): ''' Tries to smartly find the absolute path of a config file. If the given path is absolute and exists return it unmodified, otherwise do usual leaf based lookup If the given path contains only a file name check for existence in LOAD_ORDER dirs returning if found If the given path contains a relative filepath check for existence in LOAD_ORDER joining each with the fragement ''' path = PosixPath(path) if path.is_absolute() and path.exists(): return path for confDir in LOAD_ORDER: if confDir.joinpath(path).exists(): return confDir.joinpath(path).resolve() return None
def strip_root(path: pathlib.PurePath) -> pathlib.PurePosixPath: """Turn the path into a relative path by stripping the root. This also turns any drive letter into a normal path component. This changes "C:/Program Files/Blender" to "C/Program Files/Blender", and "/absolute/path.txt" to "absolute/path.txt", making it possible to treat it as a relative path. """ if path.drive: return pathlib.PurePosixPath(path.drive[0], *path.parts[1:]) if isinstance(path, pathlib.PurePosixPath): # This happens when running on POSIX but still handling paths # originating from a Windows machine. parts = path.parts if parts and len(parts[0]) == 2 and parts[0][0].isalpha() and parts[0][1] == ':': # The first part is a drive letter. return pathlib.PurePosixPath(parts[0][0], *path.parts[1:]) if path.is_absolute(): return pathlib.PurePosixPath(*path.parts[1:]) return pathlib.PurePosixPath(path)
def find_path_in( self, path: fs.PathLike, search_prefixes: Optional[Iterable[fs.PathLike]] = None ) -> Optional[fs.Path]: # noinspection PyMethodFirstArgAssignment self = _get_root_specifics() if not isinstance(path, fs.Path): path = fs.Path(path) if path.is_absolute(): raise ValueError("'path' must not be absolute") if search_prefixes is None: prefixes = self._executable_search_paths else: prefixes = [] if isinstance(search_prefixes, (str, bytes)): raise TypeError( "'search_prefixes' must be iterable (other than 'str' or 'bytes')" ) for p in search_prefixes: if not isinstance(p, fs.Path): p = fs.Path(p, is_dir=True) if not p.is_dir(): raise ValueError(f"not a directory: {p.as_string()!r}") if not p.is_absolute(): p = self._root_path / p prefixes.append(p) for prefix in prefixes: p = prefix / path try: if path.is_dir() == stat.S_ISDIR(os.stat(p.native).st_mode): return p # absolute except (ValueError, OSError): pass
def _clean_settings_path( p ): path = Path(p) if path.is_absolute() or str(path).startswith("@"): return p else: return str( Path( json_path ).parent.joinpath(p).resolve() )
def load_file(self, f, triangulate=True): """Loads models from file object Triangulates faces if *triangulate* specified""" mtl_loader = MTLLoader() for i, line in enumerate(f): if line.startswith("#"): continue try: op, *params = line.split() except ValueError: continue if op == "v": t = tuple(map(float, params)) assert len(t) == 3 self.get_obj().v.append(t) elif op == "vt": t = tuple(map(float, params)) assert len(t) == 2 self.get_obj().vt.append(t) elif op == "vn": t = Vec(map(float, params)) assert len(t) == 3 t.normalize() self.get_obj().vn.append(t) elif op == "f": if triangulate: #params = list( # map(lambda x: tuple(map(index_or_none, x.split("/"))), params) #) params = [[ None if not v.isnumeric() else int(v) - 1 if int(v) > 0 else int(v) for v in x.split("/") ] for x in params] for i in range(len(params) - 2): t = [] t.extend(params[0]) t.extend(params[i + 1]) t.extend(params[i + 2]) self.get_sub_obj().f.append(t) else: t = [] for p in params: t.extend(map(index_or_none, p.split("/"))) self.get_sub_obj().f.append(t) elif op == "usemtl": self.current_material = params[0] elif op == "mtllib": path = pathlib.Path(line.split(maxsplit=1)[1].strip()) logger.info("Loading mtlib from %s", path) if path.is_absolute(): pass else: path = pathlib.Path(self.loads_from).parent.joinpath(path) mtl_loader.load_path(path) elif op == "o": if len(params) > 0: self.current_object = params[0] else: self.current_object = len(self.objects.keys()) else: logger.warning("Unsapported op %s", op) self.materials.update(mtl_loader.materials)
def file_path(self, file_name): path = Path(getattr(self, file_name + "_path")) if not path.is_absolute(): path = FragSimConf.CFM_ID_FOLDER / path return str(path)
def get_abs_path(path): assert (isinstance(path, pathlib.PurePath)) if path.is_absolute(): return path return pathlib.Path.cwd().joinpath(path)
def abspath_from_conf(cf_path: Path, path: Path): return (path if path.is_absolute() else cf_path.parent.joinpath(path)).resolve()
def fix_path(path_str, workdir): path = Path(path_str) path = path if path.is_absolute() else workdir / path return str(path)
def working_tree_path_of( self, path: fs.PathLike, *, is_dir: Optional[bool] = None, existing: bool = False, collapsable: bool = False, allow_temporary: bool = False, allow_nontemporary_management: bool = False) -> fs.Path: # this must be very fast for relative dlb.fs.Path with existing = True # noinspection PyMethodFirstArgAssignment self = _get_root_specifics() if not isinstance( path, fs.Path) or is_dir is not None and is_dir != path.is_dir(): path = fs.Path(path, is_dir=is_dir) if path.is_absolute(): # note: do _not_ used path.resolve() or os.path.realpath(), since it would resolve the entire path native_components = path.native.components # may raise PathNormalizationError normalized_native_components = \ (native_components[0],) + \ _worktree.normalize_dotdot_native_components(native_components[1:], ref_dir_path=native_components[0]) native_root_path_components = self._root_path.native.components n = len(native_root_path_components) if normalized_native_components[:n] != native_root_path_components: raise _error.WorkingTreePathError( "does not start with the working tree's root path") rel_components = ('', ) + normalized_native_components[n:] else: # 'collapsable' means only the part relative to the working tree's root ref_dir_path = None if collapsable else self._root_path_native_str rel_components = ( '', ) + _worktree.normalize_dotdot_native_components( path.components[1:], ref_dir_path=ref_dir_path) if len(rel_components) > 1 and rel_components[ 1] == _worktree.MANAGEMENTTREE_DIR_NAME: if len(rel_components ) > 2 and rel_components[2] == _worktree.TEMPORARY_DIR_NAME: permitted = allow_temporary else: permitted = allow_nontemporary_management if not permitted: msg = f"path in non-permitted part of the working tree: {path.as_string()!r}" raise _error.WorkingTreePathError(msg) # may raise ValueError rel_path = path.__class__(rel_components, is_dir=path.is_dir( )) if path.components != rel_components else path if not existing: try: s = str(rel_path.native) if s[:2] == '.' + os.path.sep: s = s[2:] sr = os.lstat(os.path.sep.join([self._root_path_native_str, s])) is_dir = stat.S_ISDIR(sr.st_mode) except OSError as e: raise _error.WorkingTreePathError(oserror=e) from None if is_dir != rel_path.is_dir(): rel_path = path.__class__(rel_components, is_dir=is_dir) return rel_path