Move common_pb2.Path->pathlib.Path converter
Previously I had implemented a helper function that converts
common_pb2.Path objects into pathlib.Path objects. I put that function
in lib/path_util.py, since it is a little utility relating to paths.
However, based on feedback in the attached bug, it seems that lib/
should not rely on protobufs. Thus, this CL moves the function into
api/.
I've also renamed the function to be consistent with Chromite's newer
snake_case guidance, and I've renamed some internal variable names for
the sake of clarity.
BUG=b:268732304
TEST=./run_tests
Change-Id: I203ba6c278cd043b2732a132ee19befa451e08ec
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/4389805
Commit-Queue: Greg Edelston <gredelston@google.com>
Tested-by: Greg Edelston <gredelston@google.com>
Auto-Submit: Greg Edelston <gredelston@google.com>
Reviewed-by: Alex Klein <saklein@chromium.org>
diff --git a/api/controller/controller_util.py b/api/controller/controller_util.py
index 0476676..b7da66c 100644
--- a/api/controller/controller_util.py
+++ b/api/controller/controller_util.py
@@ -296,3 +296,32 @@
p = package_info_msg.package_name
v = ("-%s" % package_info_msg.version) if package_info_msg.version else ""
return "%s%s%s" % (c, p, v)
+
+
+def pb2_path_to_pathlib_path(
+ pb2_path: "common_pb2.Path",
+ chroot: Optional["common_pb2.Chroot"] = None,
+) -> Path:
+ """Convert an absolute pb2 path to a pathlib.Path outside the chroot.
+
+ Args:
+ pb2_path: An absolute path, which might be inside or outside chroot.
+ chroot: The chroot that the path might be inside of.
+
+ Returns:
+ A Path pointing to the same location as pb2_path, originating
+ outside the chroot.
+
+ Raises:
+ ValueError: If the given path is relative instead of absolute.
+ ValueError: If the given path is inside the chroot, but a chroot is not
+ provided.
+ """
+ if pb2_path.path[0] != "/":
+ raise ValueError(f"Cannot convert relative path: {pb2_path.path}")
+ if pb2_path.location is common_pb2.Path.Location.OUTSIDE:
+ return Path(pb2_path.path)
+ if chroot is None:
+ raise ValueError("Cannot convert inside path without a chroot.")
+ path_relative_to_root = pb2_path.path[1:]
+ return Path(chroot.path, path_relative_to_root)