Skip to content

Commit

Permalink
utils: backport replace_root
Browse files Browse the repository at this point in the history
  • Loading branch information
Bodong-Yang committed Mar 4, 2024
1 parent 0144a64 commit 7dea273
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions otaclient/_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@


from __future__ import annotations
import os
from math import ceil
from pathlib import Path
from typing import Any, Callable, Optional, TypeVar
Expand Down Expand Up @@ -66,3 +67,21 @@ def get_file_size(
swapfile_fpath = Path(swapfile_fpath)
if swapfile_fpath.is_file():
return ceil(swapfile_fpath.stat().st_size / _multiplier[units])


def replace_root(path: str | Path, old_root: str | Path, new_root: str | Path) -> str:
"""Replace a <path> relative to <old_root> to <new_root>.
For example, if path="/abc", old_root="/", new_root="/new_root",
then we will have "/new_root/abc".
"""
# normalize all the input args
path = os.path.normpath(path)
old_root = os.path.normpath(old_root)
new_root = os.path.normpath(new_root)

if not (old_root.startswith("/") and new_root.startswith("/")):
raise ValueError(f"{old_root=} and/or {new_root=} is not valid root")
if os.path.commonpath([path, old_root]) != old_root:
raise ValueError(f"{old_root=} is not the root of {path=}")
return os.path.join(new_root, os.path.relpath(path, old_root))

0 comments on commit 7dea273

Please sign in to comment.