๐Ÿ“ฆ astral-sh / ty

๐Ÿ“„ update_schemastore.py ยท 197 lines
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
194
195
196
197"""Update ty.json in schemastore.

This script will clone `astral-sh/schemastore`, update the schema and push the changes
to a new branch tagged with the ty git hash. You should see a URL to create the PR
to schemastore in the CLI.

Usage:

    uv run --only-dev scripts/update_schemastore.py
"""

from __future__ import annotations

import enum
import json
from pathlib import Path
from subprocess import check_call, check_output
from tempfile import TemporaryDirectory
from typing import NamedTuple, assert_never

# The remote URL for the `ty` repository.
TY_REPO = "https://github.com/astral-sh/ty"

# The path to the root of the `ty` repository.
TY_ROOT = Path(__file__).parent.parent

# The path to the JSON schema in the `ty` repository.
TY_SCHEMA = TY_ROOT / "ruff" / "ty.schema.json"

# The path to the JSON schema in the `schemastore` repository.
TY_JSON = Path("schemas/json/ty.json")


class SchemastoreRepos(NamedTuple):
    fork: str
    upstream: str


class GitProtocol(enum.Enum):
    SSH = "ssh"
    HTTPS = "https"

    def schemastore_repos(self) -> SchemastoreRepos:
        match self:
            case GitProtocol.SSH:
                return SchemastoreRepos(
                    fork="git@github.com:astral-sh/schemastore.git",
                    upstream="git@github.com:SchemaStore/schemastore.git",
                )
            case GitProtocol.HTTPS:
                return SchemastoreRepos(
                    fork="https://github.com/astral-sh/schemastore.git",
                    upstream="https://github.com/SchemaStore/schemastore.git",
                )
            case _:
                assert_never(self)


def update_schemastore(
    schemastore_path: Path, schemastore_repos: SchemastoreRepos
) -> None:
    if not (schemastore_path / ".git").is_dir():
        check_call(
            ["git", "clone", schemastore_repos.fork, schemastore_path, "--depth=1"],
        )
        check_call(
            [
                "git",
                "remote",
                "add",
                "upstream",
                schemastore_repos.upstream,
            ],
            cwd=schemastore_path,
        )

    # Create a new branch tagged with the current ty commit up to date with the latest
    # upstream schemastore
    check_call(["git", "fetch", "upstream"], cwd=schemastore_path)
    current_sha = check_output(
        ["git", "rev-parse", "HEAD"], text=True, cwd=TY_ROOT
    ).strip()
    branch = f"update-ty-{current_sha}"
    check_call(
        ["git", "switch", "-c", branch],
        cwd=schemastore_path,
    )
    check_call(
        ["git", "reset", "--hard", "upstream/master"],
        cwd=schemastore_path,
    )

    # Run npm ci
    src = schemastore_path / "src"
    check_call(["npm", "ci", "--ignore-scripts"], cwd=schemastore_path)

    # Update the schema and format appropriately
    schema = json.loads(TY_SCHEMA.read_text())
    schema["$id"] = "https://json.schemastore.org/ty.json"
    (src / TY_JSON).write_text(
        json.dumps(dict(schema.items()), indent=2, ensure_ascii=False),
    )
    check_call(
        [
            "../node_modules/prettier/bin/prettier.cjs",
            "--plugin",
            "prettier-plugin-sort-json",
            "--write",
            TY_JSON,
        ],
        cwd=src,
    )

    # Check if the schema has changed
    # https://stackoverflow.com/a/9393642/3549270
    if check_output(["git", "status", "-s"], cwd=schemastore_path).strip():
        # Schema has changed, commit and push
        commit_url = f"{TY_REPO}/commit/{current_sha}"
        commit_body = f"This updates ty's JSON schema to [{current_sha}]({commit_url})"
        # https://stackoverflow.com/a/22909204/3549270
        check_call(["git", "add", (src / TY_JSON).as_posix()], cwd=schemastore_path)
        check_call(
            [
                "git",
                "commit",
                "-m",
                "Update ty's JSON schema",
                "-m",
                commit_body,
            ],
            cwd=schemastore_path,
        )
        # This should show the link to create a PR
        check_call(
            ["git", "push", "--set-upstream", "origin", branch, "--force"],
            cwd=schemastore_path,
        )
    else:
        print("No changes")


def determine_git_protocol(argv: list[str] | None = None) -> GitProtocol:
    import argparse

    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "--proto",
        choices=[proto.value for proto in GitProtocol],
        default="https",
        help="Protocol to use for git authentication",
    )
    args = parser.parse_args(argv)
    return GitProtocol(args.proto)


def main() -> None:
    expected_ruff_revision = check_output(
        ["git", "ls-tree", "main", "--format", "%(objectname)", "ruff"], cwd=TY_ROOT
    ).strip()
    actual_ruff_revision = check_output(
        ["git", "-C", "ruff", "rev-parse", "HEAD"], cwd=TY_ROOT
    ).strip()

    if expected_ruff_revision != actual_ruff_revision:
        print(
            f"The ruff submodule is at {actual_ruff_revision} but main expects {expected_ruff_revision}"
        )
        match input(
            "How do you want to proceed (u=reset submodule, n=abort, y=continue)? "
        ):
            case "u":
                check_call(
                    ["git", "-C", "ruff", "reset", "--hard", expected_ruff_revision],
                    cwd=TY_ROOT,
                )
            case "n":
                return
            case "y":
                ...
            case command:
                print(f"Invalid input '{command}', abort")
                return

    schemastore_repos = determine_git_protocol().schemastore_repos()
    schemastore_existing = TY_ROOT / "schemastore"
    if schemastore_existing.is_dir():
        update_schemastore(schemastore_existing, schemastore_repos)
    else:
        with TemporaryDirectory(prefix="ty-schemastore-") as temp_dir:
            update_schemastore(Path(temp_dir), schemastore_repos)


if __name__ == "__main__":
    main()