1# Copyright (C) 2018 The Android Open Source Project
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#      http://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"""Tool functions to deal with files."""
15
16import datetime
17import os
18
19from google.protobuf import text_format    # pylint: disable=import-error
20
21import metadata_pb2    # pylint: disable=import-error
22
23ANDROID_TOP = os.environ.get('ANDROID_BUILD_TOP', os.getcwd())
24EXTERNAL_PATH = os.path.join(ANDROID_TOP, 'external/')
25
26METADATA_FILENAME = 'METADATA'
27
28
29def get_absolute_project_path(project_path):
30    """Gets absolute path of a project.
31
32    Path resolution starts from external/.
33    """
34    return os.path.join(EXTERNAL_PATH, project_path)
35
36
37def get_metadata_path(project_path):
38    """Gets the absolute path of METADATA for a project."""
39    return os.path.join(
40        get_absolute_project_path(project_path), METADATA_FILENAME)
41
42
43def get_relative_project_path(project_path):
44    """Gets the relative path of a project starting from external/."""
45    project_path = get_absolute_project_path(project_path)
46    return os.path.relpath(project_path, EXTERNAL_PATH)
47
48
49def read_metadata(proj_path):
50    """Reads and parses METADATA file for a project.
51
52    Args:
53      proj_path: Path to the project.
54
55    Returns:
56      Parsed MetaData proto.
57
58    Raises:
59      text_format.ParseError: Occurred when the METADATA file is invalid.
60      FileNotFoundError: Occurred when METADATA file is not found.
61    """
62
63    with open(get_metadata_path(proj_path), 'r') as metadata_file:
64        metadata = metadata_file.read()
65        return text_format.Parse(metadata, metadata_pb2.MetaData())
66
67
68def write_metadata(proj_path, metadata):
69    """Writes updated METADATA file for a project.
70
71    This function updates last_upgrade_date in metadata and write to the project
72    directory.
73
74    Args:
75      proj_path: Path to the project.
76      metadata: The MetaData proto to write.
77    """
78
79    date = metadata.third_party.last_upgrade_date
80    now = datetime.datetime.now()
81    date.year = now.year
82    date.month = now.month
83    date.day = now.day
84    text_metadata = text_format.MessageToString(metadata)
85    with open(get_metadata_path(proj_path), 'w') as metadata_file:
86        metadata_file.write(text_metadata)
87