1# Copyright 2021 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
16import pathlib
17import shutil
18import subprocess
19import tempfile
20
21import describe
22import changesummary
23
24
25SCRIPTS_DIR = pathlib.Path(__file__).parent.resolve()
26DISCOVERY_DOC_DIR = (
27    SCRIPTS_DIR / ".." / "googleapiclient" / "discovery_cache" / "documents"
28)
29REFERENCE_DOC_DIR = SCRIPTS_DIR / ".." / "docs" / "dyn"
30TEMP_DIR = SCRIPTS_DIR / "temp"
31
32# Clear discovery documents and reference documents directory
33shutil.rmtree(DISCOVERY_DOC_DIR, ignore_errors=True)
34shutil.rmtree(REFERENCE_DOC_DIR, ignore_errors=True)
35
36# Clear temporary directory
37shutil.rmtree(TEMP_DIR, ignore_errors=True)
38
39# Check out a fresh copy
40subprocess.call(["git", "checkout", DISCOVERY_DOC_DIR])
41subprocess.call(["git", "checkout", REFERENCE_DOC_DIR])
42
43# Snapshot current discovery artifacts to a temporary directory
44with tempfile.TemporaryDirectory() as current_discovery_doc_dir:
45    shutil.copytree(DISCOVERY_DOC_DIR, current_discovery_doc_dir, dirs_exist_ok=True)
46
47    # Download discovery artifacts and generate documentation
48    describe.generate_all_api_documents()
49
50    # Get a list of files changed using `git diff`
51    git_diff_output = subprocess.check_output(
52        [
53            "git",
54            "diff",
55            "origin/main",
56            "--name-only",
57            "--",
58            DISCOVERY_DOC_DIR / "*.json",
59            REFERENCE_DOC_DIR / "*.html",
60            REFERENCE_DOC_DIR / "*.md",
61        ],
62        universal_newlines=True,
63    )
64
65    # Create lists of the changed files
66    all_changed_files = [
67        pathlib.Path(file_name).name for file_name in git_diff_output.split("\n")
68    ]
69    json_changed_files = [file for file in all_changed_files if file.endswith(".json")]
70
71    # Create temporary directory
72    pathlib.Path(TEMP_DIR).mkdir()
73
74    # Analyze the changes in discovery artifacts using the changesummary module
75    changesummary.ChangeSummary(
76        DISCOVERY_DOC_DIR, current_discovery_doc_dir, TEMP_DIR, json_changed_files
77    ).detect_discovery_changes()
78
79    # Write a list of the files changed to a file called `changed files` which will be used in the `createcommits.sh` script.
80    with open(TEMP_DIR / "changed_files", "w") as f:
81        f.writelines("\n".join(all_changed_files))
82