def swap_dir(rootpath, path): """Swap a symlink with its target directory. Args: rootpath: Rootpath for tag conversions. path: Path of target symlink. """ target = path if posixpath.islink(target) and posixpath.isdir(target): here = target there = pathlib.readlink(target) # here is the symlink # there is the dir here_tag = tagnames.path2tag(rootpath, here) there_tag = tagnames.path2tag(rootpath, there) dtags.remove_tag(here, here_tag) dtags.add_tag(here, there_tag) os.unlink(here) # here is now nothing # there is now the dir os.rename(there, here) # here is now the dir # there is now nothing os.symlink(here, there) else: raise ValueError('{} is not a symlink to a directory'.format(target))
def unload_dtags(rootpath, dirpath): """Remove symlinks using a directory's dtags.""" tags = dtags.list_tags(dirpath) dirpath = pathlib.readlink(dirpath) for tagname in tags: tagpath = tagnames.tag2path(rootpath, tagname) if posixpath.samefile(dirpath, tagpath): os.unlink(tagpath)
def load_dtags(rootpath, dirpath): """Create symlinks for a directory using its dtags.""" tags = dtags.list_tags(dirpath) dirpath = pathlib.readlink(dirpath) target = posixpath.abspath(dirpath) for tagname in tags: dstpath = tagnames.tag2path(rootpath, tagname) os.symlink(target, dstpath)
def link(rootpath, src, dst): """Link src to dst. Args: rootpath: Path for tagname conversions. src: Source path. dst: Destination path. """ if posixpath.isdir(src): src = pathlib.readlink(src) os.symlink(posixpath.abspath(src), dst) dtags.add_tag(src, tagnames.path2tag(rootpath, dst)) else: os.link(src, dst)
def save_dtags(rootpath, top, dirpath): """Save symlinks to a directory's dtags, overwriting it. Args: rootpath: Path for tag conversions. top: Path of directory in which to search. dirpath: Path of directory whose dtags to update. """ dirpath = pathlib.readlink(dirpath) tags = [tagnames.path2tag(rootpath, path) for path in list_links(top, dirpath)] dir_tagname = tagnames.path2tag(rootpath, dirpath) tags = [tagname for tagname in tags if tagname != dir_tagname] dtags.set_tags(dirpath, tags)
def unlink_all(rootpath, top, path): """Unlink all links to the target file-or-directory. Unlink all links to the target under top. Args: rootpath: Base path for tag conversions and search. top: Path of search directory. path: Path to target. """ target = path if posixpath.isdir(target): target = pathlib.readlink(target) base.unload_dtags(rootpath, target) shutil.rmtree(target) else: for path in base.list_links(top, target): base.unlink(rootpath, path)