aboutsummaryrefslogtreecommitdiff
path: root/scripts/gen_release_table.py
blob: 892861c5fbe41a97942009862fc4690020269892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Generates an HTML table for the downloads page."""
from __future__ import annotations

import argparse
from dataclasses import dataclass, field
import logging
from pathlib import Path
import re
import sys
from typing import Optional


# pylint: disable=design


def get_lines():
    """Returns all stdin input until the first empty line."""
    lines = []
    while True:
        line = input()
        if line.strip() == "":
            return lines
        lines.append(line)


def parse_args():
    """Parses and returns command line arguments."""
    parser = argparse.ArgumentParser()

    release_type_group = parser.add_mutually_exclusive_group()

    release_type_group.add_argument(
        "--beta", action="store_true", help="Generate content for a beta release."
    )

    release_type_group.add_argument(
        "--lts", action="store_true", help="Generate content for an LTS release."
    )

    return parser.parse_args()


@dataclass(frozen=True, order=True)
class Artifact:
    sort_index: int = field(init=False, repr=True)
    host: str
    package: str
    size: int
    sha: str

    def __post_init__(self):
        sort_order = {"windows": 1, "darwin": 2, "linux": 3}
        object.__setattr__(self, "sort_index", sort_order.get(self.host, 4))

    @property
    def pretty_host(self) -> str:
        return {
            "darwin": "macOS",
            "linux": "Linux",
            "windows": "Windows",
        }[self.host]

    @classmethod
    def from_line(cls, line: str) -> Optional[Artifact]:
        # Some lines are updates to the repository.xml files used by the SDK
        # manager. We don't care about these.
        # <sha>        12,345  path/to/repository.xml
        if line.endswith(".xml") or "android-ndk" not in line:
            return None

        # Real entries look like this (the leading hex number is optional):
        # 0x1234 <sha>   123,456,789  path/to/android-ndk-r23-beta5-linux.zip
        match = re.match(r"^(?:0x[0-9a-f]+)?\s*(\w+)\s+([0-9,]+)\s+(.+)$", line)
        if match is None:
            logging.error("Skipping unrecognized line: %s", line)
            return None

        sha = match.group(1)

        size_str = match.group(2)
        size = int(size_str.replace(",", ""))

        path = Path(match.group(3))
        if path.suffix == ".zip" and "darwin" in path.name:
            # Ignore. We only publish the DMG on the web page.
            return None

        return Artifact(cls.host_from_package_path(path), path.name, size, sha)

    @staticmethod
    def host_from_package_path(path: Path) -> str:
        # android-ndk-$VERSION-$HOST.$EXT
        # $VERSION might contain a hyphen for beta/RC releases.
        # Split on all hyphens and join $HOST and $EXT to get the platform.
        return path.stem.split("-")[-1]


def main():
    """Program entry point."""
    args = parse_args()
    print(
        'Paste the contents of the "New files" section of the SDK update '
        "email here. Terminate with an empty line."
    )
    lines = get_lines()
    if not lines:
        sys.exit("No input.")

    # The user may have pasted the following header line:
    # SHA1                                              size  file
    if lines[0].startswith("SHA1") or lines[0].lstrip().startswith("Link"):
        lines = lines[1:]

    artifacts = []
    for line in lines:
        if (artifact := Artifact.from_line(line)) is not None:
            artifacts.append(artifact)

    # Sort the artifacts by the specific order.
    artifacts = sorted(artifacts)

    print("For GitHub:")
    print("<table>")
    print("  <tr>")
    print("    <th>Platform</th>")
    print("    <th>Package</th>")
    print("    <th>Size (Bytes)</th>")
    print("    <th>SHA1 Checksum</th>")
    print("  </tr>")
    for artifact in artifacts:
        url_base = "https://dl.google.com/android/repository/"
        package_url = url_base + artifact.package
        link = '<a href="{}">{}</a>'.format(package_url, artifact.package)

        print("  <tr>")
        print("    <td>{}</td>".format(artifact.pretty_host))
        print("    <td>{}</td>".format(link))
        print("    <td>{}</td>".format(artifact.size))
        print("    <td>{}</td>".format(artifact.sha))
        print("  </tr>")
    print("</table>")
    print()
    print("For DAC:")

    if args.beta:
        var_prefix = "ndk_beta"
    elif args.lts:
        var_prefix = "ndk_lts"
    else:
        var_prefix = "ndk"
    for artifact in artifacts:
        dac_host = {
            "darwin": "mac64_dmg",
            "linux": "linux64",
            "windows": "win64",
        }[artifact.host]
        print()
        print("{{# {} #}}".format(artifact.pretty_host))
        print(
            "{{% setvar {}_{}_download %}}{}{{% endsetvar %}}".format(
                var_prefix, dac_host, artifact.package
            )
        )
        print(
            "{{% setvar {}_{}_bytes %}}{}{{% endsetvar %}}".format(
                var_prefix, dac_host, artifact.size
            )
        )
        print(
            "{{% setvar {}_{}_checksum %}}{}{{% endsetvar %}}".format(
                var_prefix, dac_host, artifact.sha
            )
        )


if __name__ == "__main__":
    main()