From 7dea2735251a9e0af5fcbf450c14dcebaa894ce3 Mon Sep 17 00:00:00 2001 From: Bodong YANG Date: Mon, 4 Mar 2024 09:32:07 +0000 Subject: [PATCH] utils: backport replace_root --- otaclient/_utils/__init__.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/otaclient/_utils/__init__.py b/otaclient/_utils/__init__.py index c4cb3ca96..3be3b5bf7 100644 --- a/otaclient/_utils/__init__.py +++ b/otaclient/_utils/__init__.py @@ -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 @@ -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 relative to to . + + 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))