xref: /aosp_15_r20/external/google-cloud-java/owl-bot-postprocessor/synthtool/languages/common.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
15import json
16from pathlib import Path
17import re
18
19
20def update_library_version(version: str, root_dir: str):
21    """
22    Rewrites all metadata files in ./samples/generated to the version number argument
23
24    """
25    root_dir_path = Path(root_dir)
26
27    snippet_metadata_files = get_sample_metadata_files(root_dir_path)
28    for file in snippet_metadata_files:
29        with open(file, "r+") as f:
30            data = json.load(f)
31            data["clientLibrary"]["version"] = version
32            f.seek(0)
33            json.dump(data, f, indent=4)
34            f.truncate()
35
36
37def get_sample_metadata_files(dir: Path, regex: str = r"snippet_metadata"):
38    """
39    Walks through samples/generated to find all snippet metadata files, appends them to a list
40
41    Returns:
42    A list of all metadata files.
43    """
44    metadata_files = []
45    for path_object in dir.glob("**/*"):
46        if path_object.is_file():
47            if re.search(regex, str(path_object)):
48                metadata_files.append(str(Path(path_object).resolve()))
49        if path_object.is_dir():
50            get_sample_metadata_files(path_object)
51
52    return metadata_files
53