xref: /aosp_15_r20/external/google-cloud-java/owl-bot-postprocessor/synthtool/_tracked_paths.py (revision 55e87721aa1bc457b326496a7ca40f3ea1a63287)
1# Copyright 2018 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Tracked paths.
16
17This is a bit of a hack.
18"""
19
20import pathlib
21
22
23_tracked_paths = []
24
25
26def add(path):
27    _tracked_paths.append(pathlib.Path(path))
28    # Reverse sort the list, so that the deepest paths get matched first.
29    _tracked_paths.sort(key=lambda s: -len(str(s)))
30
31
32def relativize(path):
33    path = pathlib.Path(path)
34    for tracked_path in _tracked_paths:
35        try:
36            return path.relative_to(tracked_path)
37        except ValueError:
38            pass
39    raise ValueError(f"The root for {path} is not tracked.")
40