def validate_abspath(self, value: str) -> None: if any([ntpath.isabs(value), posixpath.isabs(value)]): raise ValidationError( description="found an absolute path ({}), expected a filename".format(value), platform=self.platform, reason=ErrorReason.FOUND_ABS_PATH, )
def absolute_win_path(val=ntpath.join('C:', ntpath.sep)): """Check for an absolute windows file path.""" val = str(val) if ntpath.isabs(val) and ntpath.splitdrive(val)[0]: return val raise ValueError('%r is not a valid absolute path (should start with drive' ' name like C:)' % val)
def _abspath(root, value): # not all variables are paths: only absolutize if it looks like a relative path if root and \ (value.startswith('./') or \ ('/' in value and not (posixpath.isabs(value) or ntpath.isabs(value)))): value = os.path.join(root, value) return value
def isabs(s): """Test whether a path is absolute""" if cosmo.kernel == 'nt' and '\\' in s: return ntpath.isabs(s) s = os.fspath(s) sep = _get_sep(s) return s.startswith(sep)
def resolver_backlink(self, link, linkTgt, bad_links): linkTgt_abs = absTgtpath(link, linkTgt) if not os.path.exists(linkTgt_abs): # Quietly skip return path = os.path.dirname(link) if not os.path.isdir(path): return tmp = path.split(os.sep) if not isPerson(tmp[-1]): return tmp = linkTgt_abs.split(os.sep) if not isPerson(tmp[-1]): return # Go to the linkTgt_abs directory and look for a link which has # path as its target if not findLinkTo(path, linkTgt_abs): clan, name = extractPersonName(path) # We can't determine sex here hence the 'p.' newLink = os.path.join( linkTgt_abs, 'p. %s %s' % (name.capitalize(), clan.capitalize())) # Make the new link relative if the original one was if not ntpath.isabs(linkTgt): path = os.path.relpath(path, os.path.dirname(newLink)) bad_links.append(Backlink(link, linkTgt, newLink, path))
def windows_to_native(windows_path): """ Convert a (relative) Windows path to a native path. If windows_path is not a Windows path, the result is undefined. #>>> PathTools.windows_to_native("D:\\\\foo") #'D:\\\\foo' #>>> PathTools.windows_to_native(".\\\\foo") #'.\\\\foo' #>>> PathTools.windows_to_native("D:\\\\foo") #ValueError on POSIX #>>> PathTools.windows_to_native("/foo") #'/foo' """ if os.path == posixpath: if ntpath.isabs(windows_path): raise ValueError( "Cannot convert an absolute Windows path to POSIX: %s" % windows_path) return windows_path.replace('\\', os.path.sep) elif os.path == ntpath: return windows_path else: raise NotImplementedError("Can only convert to posix or nt")
def abspath(path): if not isabs(path): if isinstance(path, unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path)
def get_top_srcdir(self, file): """Returns a normalized top_srcdir for the given file: if substs['top_srcdir'] is a relative path, it is relative to the topobjdir. Adjust it to be relative to the file path.""" top_srcdir = self.substs["top_srcdir"] if posixpath.isabs(top_srcdir) or ntpath.isabs(top_srcdir): return top_srcdir return posixpath.normpath(posixpath.join(self.get_depth(file), top_srcdir))
def _is_absolute_path(self, path): if posixpath.isabs(path): return True if ntpath.isabs(path): return True return False
def get_top_srcdir(self, file): '''Returns a normalized top_srcdir for the given file: if substs['top_srcdir'] is a relative path, it is relative to the topobjdir. Adjust it to be relative to the file path.''' top_srcdir = self.substs['top_srcdir'] if posixpath.isabs(top_srcdir) or ntpath.isabs(top_srcdir): return top_srcdir return posixpath.normpath(posixpath.join(self.get_depth(file), top_srcdir))
def _is_abs(path): """ Check if path is absolute on any platform. :param str path: Path to validate. :returns bool: True is absolute on any platform, False otherwise. """ return posixpath.isabs(path) or ntpath.isabs(path)
def abspath(path): """Return the absolute version of a path""" if not isabs(path): if isinstance(path, unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path)
def __normalize(cls, path, expand_user=False): if expand_user: path = os.path.expanduser(path) drive, path = ntpath.splitdrive(path) if drive and not ntpath.isabs(path): raise ValueError('relative paths with drives not supported') drive = drive.replace('\\', '/') path, isdir = cls.__normpath(path) return drive, path, isdir
def join(a, *p): path = a for b in p: if isabs(b): path = b if path == '' or path[-1:] in '/\\:': path = path + b path = path + '/' + b return path
def join(a, *p): path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + '/' + b return path
def join(a, *p): """Join two or more pathname components, inserting sep as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + '/' + b return path
def path2posixPath(absPathString): print('ERORR: This function was not tested yet!') exit(-1) # absPathString must be absolute path. if ntpath.isabs(absPathString): # is windows tempPath = PureWindowsPath(pathString) tempPath = Path(tempPath) if posixpath.isabs(absPathString): # is linux/mac tempPath = PurePosixPath(pathString) tempPath = Path(tempPath) return str(tempPath)
def readlink_f(linkName): # resolve links and return absolute path '''Read link target. This returns an absolute path''' if linkName.endswith(INTERNET_SCUT_SUFFIX): return readlink_url(linkName) # always absolute elif linkName.endswith(WINDOWS_SCUT_SUFFIX): tgt = readlink_scut(linkName) if not ntpath.isabs(tgt): linkName = os.path.abspath(linkName) pth = os.path.join(os.path.dirname(linkName), tgt) return pth elif os.path.islink(linkName): return os.path.realpath(linkName) # realpath ensures an absolute path raise ValueError("Can't read link target")
def validate_abspath(self, value: str) -> None: err = ValidationError( description= f"found an absolute path ({value}), expected a filename", platform=self.platform, reason=ErrorReason.FOUND_ABS_PATH, ) if self._is_universal() or self._is_windows(): if ntpath.isabs(value): raise err if posixpath.isabs(value): raise err
def _is_current_platform_abspath(path): """ Check if the path is an obsolute path for the current platform. :param str path: Path to validate. :returns bool: True if absolute for this platform, False otherwise. """ if sys.platform == "win32": # ntpath likes to consider a path starting with / to be absolute, # but it is not! return ntpath.isabs(path) and not posixpath.isabs(path) else: return posixpath.isabs(path)
def _is_current_platform_abspath(path): """ Check if the path is an obsolute path for the current platform. :param str path: Path to validate. :returns bool: True if absolute for this platform, False otherwise. """ if is_windows(): # ntpath likes to consider a path starting with / to be absolute, # but it is not! return ntpath.isabs(path) and not posixpath.isabs(path) else: return posixpath.isabs(path)
def join(a, *p): """Join two or more pathname components, inserting sep as needed. Also replaces all altsep chars with sep in the returned string to make it consistent.""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + '/' + b return path.replace(altsep, sep)
def resolve_file_path(file_path, current_dir, datapath): file_path = file_path.lstrip("\\") if ntpath.isabs(file_path): return file_path file_path = file_path.replace("\\", os.sep) relpath_base = os.path.join(os.path.realpath(datapath), file_path) # paths that contain directories are always relative to the data path if os.path.exists(relpath_base) or os.sep in file_path: return relpath_base relpath_ls3 = os.path.join(os.path.realpath(current_dir), file_path) return relpath_ls3 if os.path.exists(relpath_ls3) else relpath_base
def validate_abspath(self, value: PathType) -> None: value = str(value) is_posix_abs = posixpath.isabs(value) is_nt_abs = ntpath.isabs(value) err_object = ValidationError( description= ("an invalid absolute file path ({}) for the platform ({}).". format(value, self.platform.value) + " to avoid the error, specify an appropriate platform correspond" + " with the path format, or 'auto'."), platform=self.platform, reason=ErrorReason.MALFORMED_ABS_PATH, ) if self._is_universal() and any([is_posix_abs, is_nt_abs]): raise err_object if any([self._is_windows(), self._is_universal() ]) and posixpath.isabs(value): raise err_object drive, _tail = ntpath.splitdrive(value) if not self._is_windows() and drive and ntpath.isabs(value): raise err_object
def drive_path(path): """ split absolute paths from nt, osx, or linux into (drive, path) tuple """ path = path.replace(ntpath.sep, '/') drive, path = ntpath.splitdrive(path) if ntpath.isabs(path): split = path.split('/', 3) if split[1] in ('Volumes', 'media', 'mnt'): drive = split[2] path = '/' + split[3] elif split[1] in ('Users', 'home'): drive = drive or split[1] else: raise ValueError, split[1] drive = DRIVES.get(drive, drive) return drive, path
def __init__(self, file_prefix): # Determine what type of path it is # Ntpath includes posixpaths, so be sure to test # posix first :P if posixpath.isabs(file_prefix): self.working_directory = "/" self.emulated_path_module = posixpath elif ntpath.isabs(file_prefix): self.working_directory, _ = ntpath.splitdrive(file_prefix) self.emulated_path_module = ntpath else: raise ZelosException((f"Path {file_prefix} is not an absolute " "filepath of any system I know of.")) self.logger = logging.getLogger(__name__) self.added_files = {} self.mounted_folders = defaultdict(list)
def resolver(self, link, linkTgt, bad_links): lnk = Link(link, linkTgt) origTgt_abs = absTgtpath(lnk.link, lnk.linkTgt) if os.path.exists(origTgt_abs): # Link exists: check that it is pointing to something # within (under) the tree if origTgt_abs.find(self.treeRoot) != 0: bad_links.append(lnk) return tgt = lnk.linkTgt newTgt = tryRebaseLink(tgt, self.treeRoot, validClans=self.clans) # If the link can't be rebased then there's no further 'fixes' we can do if newTgt is None: bad_links.append(lnk) return # See if we've actually changed the link at all newTgt = os.path.normpath(newTgt) if newTgt != origTgt_abs: lnk.status += STATUS_REBASED tgt = newTgt # abs path if not os.path.exists(tgt): newTgt = self.tryGenGap(lnk.link, tgt) if newTgt is not None: tgt = newTgt lnk.status += STATUS_GENGAP if os.path.exists(tgt): lnk.status += STATUS_OK # If the original link was relative then make the revised one too if not ntpath.isabs(lnk.linkTgt): tgt = os.path.relpath(tgt, os.path.dirname(lnk.link)) if tgt != lnk.linkTgt: lnk.revisedLinkTgt = tgt bad_links.append(lnk)
def _resolve_link(path): """Internal helper function. Takes a path and follows symlinks until we either arrive at something that isn't a symlink, or encounter a path we've seen before (meaning that there's a loop). """ paths_seen = [] while islink(path): if path in paths_seen: # Already seen this path, so we must have a symlink loop return None paths_seen.append(path) # Resolve where the link points to resolved = os.readlink(path) if not isabs(resolved): dir = dirname(path) path = normpath(join(dir, resolved)) else: path = normpath(resolved) return path
def ntpath_to_mingwpath(path): if os.path is not ntpath: return path if isinstance(path,pathlib.PureWindowsPath): path = str(path) if len(path) >= 2 and path[0].isalpha() and path[1] == ':': return '/' + path[0].lower() + path[2:].replace('\\', '/') return path assert ntpath.isabs(path) drive,path = ntpath.splitdrive(path) parts = path.split('\\')[1:] if drive: parts = ['/' + drive[:-1].lower()] + parts result = posixpath.join(*parts) return result
def realpath(filename): """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.""" if isabs(filename): bits = ['/'] + filename.split('/')[1:] else: bits = [''] + filename.split('/') for i in range(2, len(bits) + 1): component = join(*bits[0:i]) # Resolve symbolic links. if islink(component): resolved = _resolve_link(component) if resolved is None: # Infinite loop -- return original component + rest of the path return abspath(join(*([component] + bits[i:]))) else: newpath = join(*([resolved] + bits[i:])) return realpath(newpath) return abspath(filename)
def directory(self, value): def _mkdir(_directory): if not _directory.endswith(_slash): _directory += _slash if checks.pathExists(_directory): if checks.isDir(_directory): self.DIRECTORY = _directory self.TEMPFILE_OBJECT = None return else: err = "Path '{V}' exists but is not a directory. ".format( V=str(value)) raise ValueError(err) else: # Does NOT exist try: os.mkdir(_directory) self.DIRECTORY = _directory return except OSError as e: err = "Unable to make temporary directory path '{V}' ({E})".format( V=str(value), E=str(e)) raise OSError(err) USAGE = "The 'directory' attribute must be a full path ending in a directory marker (slash) to an existing directory or a new directory to be created. I.e. '/dir1/dir2/'." value = str(value) if value == 'mkdtemp': self.TEMPFILE_OBJECT = tempfile.mkdtemp('.tmpdir') self.DIRECTORY = self.TEMPFILE_OBJECT + _slash return if ntpath.isabs(value): _mkdir(value) else: raise PropertyNotValidValueError(stack()[0][3], value=value, USAGE=USAGE)
def ntpath(path): assert not ntpath.isabs(path) assert not posixpath.isabs(path) return path.replace("/", "\\")
def __init__(self, path, filename): if filename and ntpath.isabs(filename): self.path, self.filename = ntpath.split(filename) else: self.filename = filename self.path = path
import ntpath file = "/my/little/pony" print "isabs", "=>", ntpath.isabs(file) print "dirname", "=>", ntpath.dirname(file) print "basename", "=>", ntpath.basename(file) print "normpath", "=>", ntpath.normpath(file) print "split", "=>", ntpath.split(file) print "join", "=>", ntpath.join(file, "zorba") ## isabs => 1 ## dirname => /my/little ## basename => pony ## normpath => \my\little\pony ## split => ('/my/little', 'pony') ## join => /my/little/pony\zorba
def path_is_abs(path): if path_is_win(path): return ntpath.isabs(path) else: return posixpath.isabs(path)
def _replace_sep(path, from_sep, to_sep): assert not ntpath.isabs(path) assert not posixpath.isabs(path) return path.replace(from_sep, to_sep)
def isabs_anywhere(filename): """Is `filename` an absolute path on any OS?""" return ntpath.isabs(filename) or posixpath.isabs(filename)
def abspath(path): """Return the absolute version of a path""" if not isabs(path): path = join(os.getcwd(), path) return normpath(path)
def ntpath(path): assert not ntpath.isabs(path) assert not posixpath.isabs(path) return path.replace('/', '\\')
def abspath(path): if not isabs(path): path = join(os.getcwd(), path) return normpath(path)