Sync fastapi docs from b5ca1324 on 2025-12-07
Issue Manager / issue-manager (push) Has been cancelled
Build Docs / changes (push) Has been cancelled
Build Docs / langs (push) Has been cancelled
Build Docs / build-docs (push) Has been cancelled
Build Docs / docs-all-green (push) Has been cancelled
Conflict detector / main (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi) (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi-slim) (push) Has been cancelled
Test Redistribute / test-redistribute-alls-green (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / test (pydantic-v1, 3.10) (push) Has been cancelled
Test / test (pydantic-v1, 3.11) (push) Has been cancelled
Test / test (pydantic-v1, 3.13) (push) Has been cancelled
Test / test (pydantic-v1, 3.8) (push) Has been cancelled
Test / test (pydantic-v1, 3.9) (push) Has been cancelled
Test / test (pydantic-v2, 3.10) (push) Has been cancelled
Test / test (pydantic-v2, 3.11) (push) Has been cancelled
Test / test (pydantic-v2, 3.12) (push) Has been cancelled
Test / test (pydantic-v2, 3.13) (push) Has been cancelled
Test / test (pydantic-v2, 3.14) (push) Has been cancelled
Test / test (pydantic-v2, 3.8) (push) Has been cancelled
Test / test (pydantic-v2, 3.9) (push) Has been cancelled
Test / coverage-combine (push) Has been cancelled
Test / check (push) Has been cancelled
Label Approved / label-approved (push) Has been cancelled
FastAPI People Contributors / job (push) Has been cancelled
FastAPI People Sponsors / job (push) Has been cancelled
Update Topic Repos / topic-repos (push) Has been cancelled
FastAPI People / job (push) Has been cancelled
Test / test (pydantic-v1, 3.12) (push) Has been cancelled
Issue Manager / issue-manager (push) Has been cancelled
Build Docs / changes (push) Has been cancelled
Build Docs / langs (push) Has been cancelled
Build Docs / build-docs (push) Has been cancelled
Build Docs / docs-all-green (push) Has been cancelled
Conflict detector / main (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi) (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi-slim) (push) Has been cancelled
Test Redistribute / test-redistribute-alls-green (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / test (pydantic-v1, 3.10) (push) Has been cancelled
Test / test (pydantic-v1, 3.11) (push) Has been cancelled
Test / test (pydantic-v1, 3.13) (push) Has been cancelled
Test / test (pydantic-v1, 3.8) (push) Has been cancelled
Test / test (pydantic-v1, 3.9) (push) Has been cancelled
Test / test (pydantic-v2, 3.10) (push) Has been cancelled
Test / test (pydantic-v2, 3.11) (push) Has been cancelled
Test / test (pydantic-v2, 3.12) (push) Has been cancelled
Test / test (pydantic-v2, 3.13) (push) Has been cancelled
Test / test (pydantic-v2, 3.14) (push) Has been cancelled
Test / test (pydantic-v2, 3.8) (push) Has been cancelled
Test / test (pydantic-v2, 3.9) (push) Has been cancelled
Test / coverage-combine (push) Has been cancelled
Test / check (push) Has been cancelled
Label Approved / label-approved (push) Has been cancelled
FastAPI People Contributors / job (push) Has been cancelled
FastAPI People Sponsors / job (push) Has been cancelled
Update Topic Repos / topic-repos (push) Has been cancelled
FastAPI People / job (push) Has been cancelled
Test / test (pydantic-v1, 3.12) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,315 @@
|
||||
import logging
|
||||
import secrets
|
||||
import subprocess
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from github import Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
github_graphql_url = "https://api.github.com/graphql"
|
||||
|
||||
|
||||
prs_query = """
|
||||
query Q($after: String) {
|
||||
repository(name: "fastapi", owner: "fastapi") {
|
||||
pullRequests(first: 100, after: $after) {
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
number
|
||||
labels(first: 100) {
|
||||
nodes {
|
||||
name
|
||||
}
|
||||
}
|
||||
author {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
title
|
||||
createdAt
|
||||
lastEditedAt
|
||||
updatedAt
|
||||
state
|
||||
reviews(first:100) {
|
||||
nodes {
|
||||
author {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class Author(BaseModel):
|
||||
login: str
|
||||
avatarUrl: str
|
||||
url: str
|
||||
|
||||
|
||||
class LabelNode(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
class Labels(BaseModel):
|
||||
nodes: list[LabelNode]
|
||||
|
||||
|
||||
class ReviewNode(BaseModel):
|
||||
author: Author | None = None
|
||||
state: str
|
||||
|
||||
|
||||
class Reviews(BaseModel):
|
||||
nodes: list[ReviewNode]
|
||||
|
||||
|
||||
class PullRequestNode(BaseModel):
|
||||
number: int
|
||||
labels: Labels
|
||||
author: Author | None = None
|
||||
title: str
|
||||
createdAt: datetime
|
||||
lastEditedAt: datetime | None = None
|
||||
updatedAt: datetime | None = None
|
||||
state: str
|
||||
reviews: Reviews
|
||||
|
||||
|
||||
class PullRequestEdge(BaseModel):
|
||||
cursor: str
|
||||
node: PullRequestNode
|
||||
|
||||
|
||||
class PullRequests(BaseModel):
|
||||
edges: list[PullRequestEdge]
|
||||
|
||||
|
||||
class PRsRepository(BaseModel):
|
||||
pullRequests: PullRequests
|
||||
|
||||
|
||||
class PRsResponseData(BaseModel):
|
||||
repository: PRsRepository
|
||||
|
||||
|
||||
class PRsResponse(BaseModel):
|
||||
data: PRsResponseData
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_token: SecretStr
|
||||
github_repository: str
|
||||
httpx_timeout: int = 30
|
||||
|
||||
|
||||
def get_graphql_response(
|
||||
*,
|
||||
settings: Settings,
|
||||
query: str,
|
||||
after: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
|
||||
variables = {"after": after}
|
||||
response = httpx.post(
|
||||
github_graphql_url,
|
||||
headers=headers,
|
||||
timeout=settings.httpx_timeout,
|
||||
json={"query": query, "variables": variables, "operationName": "Q"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
logging.error(f"Response was not 200, after: {after}")
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
data = response.json()
|
||||
if "errors" in data:
|
||||
logging.error(f"Errors in response, after: {after}")
|
||||
logging.error(data["errors"])
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
return data
|
||||
|
||||
|
||||
def get_graphql_pr_edges(
|
||||
*, settings: Settings, after: str | None = None
|
||||
) -> list[PullRequestEdge]:
|
||||
data = get_graphql_response(settings=settings, query=prs_query, after=after)
|
||||
graphql_response = PRsResponse.model_validate(data)
|
||||
return graphql_response.data.repository.pullRequests.edges
|
||||
|
||||
|
||||
def get_pr_nodes(settings: Settings) -> list[PullRequestNode]:
|
||||
pr_nodes: list[PullRequestNode] = []
|
||||
pr_edges = get_graphql_pr_edges(settings=settings)
|
||||
|
||||
while pr_edges:
|
||||
for edge in pr_edges:
|
||||
pr_nodes.append(edge.node)
|
||||
last_edge = pr_edges[-1]
|
||||
pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor)
|
||||
return pr_nodes
|
||||
|
||||
|
||||
class ContributorsResults(BaseModel):
|
||||
contributors: Counter[str]
|
||||
translation_reviewers: Counter[str]
|
||||
translators: Counter[str]
|
||||
authors: dict[str, Author]
|
||||
|
||||
|
||||
def get_contributors(pr_nodes: list[PullRequestNode]) -> ContributorsResults:
|
||||
contributors = Counter[str]()
|
||||
translation_reviewers = Counter[str]()
|
||||
translators = Counter[str]()
|
||||
authors: dict[str, Author] = {}
|
||||
|
||||
for pr in pr_nodes:
|
||||
if pr.author:
|
||||
authors[pr.author.login] = pr.author
|
||||
is_lang = False
|
||||
for label in pr.labels.nodes:
|
||||
if label.name == "lang-all":
|
||||
is_lang = True
|
||||
break
|
||||
for review in pr.reviews.nodes:
|
||||
if review.author:
|
||||
authors[review.author.login] = review.author
|
||||
if is_lang:
|
||||
translation_reviewers[review.author.login] += 1
|
||||
if pr.state == "MERGED" and pr.author:
|
||||
if is_lang:
|
||||
translators[pr.author.login] += 1
|
||||
else:
|
||||
contributors[pr.author.login] += 1
|
||||
return ContributorsResults(
|
||||
contributors=contributors,
|
||||
translation_reviewers=translation_reviewers,
|
||||
translators=translators,
|
||||
authors=authors,
|
||||
)
|
||||
|
||||
|
||||
def get_users_to_write(
|
||||
*,
|
||||
counter: Counter[str],
|
||||
authors: dict[str, Author],
|
||||
min_count: int = 2,
|
||||
) -> dict[str, Any]:
|
||||
users: dict[str, Any] = {}
|
||||
for user, count in counter.most_common():
|
||||
if count >= min_count:
|
||||
author = authors[user]
|
||||
users[user] = {
|
||||
"login": user,
|
||||
"count": count,
|
||||
"avatarUrl": author.avatarUrl,
|
||||
"url": author.url,
|
||||
}
|
||||
return users
|
||||
|
||||
|
||||
def update_content(*, content_path: Path, new_content: Any) -> bool:
|
||||
old_content = content_path.read_text(encoding="utf-8")
|
||||
|
||||
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
|
||||
if old_content == new_content:
|
||||
logging.info(f"The content hasn't changed for {content_path}")
|
||||
return False
|
||||
content_path.write_text(new_content, encoding="utf-8")
|
||||
logging.info(f"Updated {content_path}")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
logging.info(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.github_token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
|
||||
pr_nodes = get_pr_nodes(settings=settings)
|
||||
contributors_results = get_contributors(pr_nodes=pr_nodes)
|
||||
authors = contributors_results.authors
|
||||
|
||||
top_contributors = get_users_to_write(
|
||||
counter=contributors_results.contributors,
|
||||
authors=authors,
|
||||
)
|
||||
|
||||
top_translators = get_users_to_write(
|
||||
counter=contributors_results.translators,
|
||||
authors=authors,
|
||||
)
|
||||
top_translations_reviewers = get_users_to_write(
|
||||
counter=contributors_results.translation_reviewers,
|
||||
authors=authors,
|
||||
)
|
||||
|
||||
# For local development
|
||||
# contributors_path = Path("../docs/en/data/contributors.yml")
|
||||
contributors_path = Path("./docs/en/data/contributors.yml")
|
||||
# translators_path = Path("../docs/en/data/translators.yml")
|
||||
translators_path = Path("./docs/en/data/translators.yml")
|
||||
# translation_reviewers_path = Path("../docs/en/data/translation_reviewers.yml")
|
||||
translation_reviewers_path = Path("./docs/en/data/translation_reviewers.yml")
|
||||
|
||||
updated = [
|
||||
update_content(content_path=contributors_path, new_content=top_contributors),
|
||||
update_content(content_path=translators_path, new_content=top_translators),
|
||||
update_content(
|
||||
content_path=translation_reviewers_path,
|
||||
new_content=top_translations_reviewers,
|
||||
),
|
||||
]
|
||||
|
||||
if not any(updated):
|
||||
logging.info("The data hasn't changed, finishing.")
|
||||
return
|
||||
|
||||
logging.info("Setting up GitHub Actions git user")
|
||||
subprocess.run(["git", "config", "user.name", "github-actions"], check=True)
|
||||
subprocess.run(
|
||||
["git", "config", "user.email", "github-actions@github.com"], check=True
|
||||
)
|
||||
branch_name = f"fastapi-people-contributors-{secrets.token_hex(4)}"
|
||||
logging.info(f"Creating a new branch {branch_name}")
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
|
||||
logging.info("Adding updated file")
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"add",
|
||||
str(contributors_path),
|
||||
str(translators_path),
|
||||
str(translation_reviewers_path),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
logging.info("Committing updated file")
|
||||
message = "👥 Update FastAPI People - Contributors and Translators"
|
||||
subprocess.run(["git", "commit", "-m", message], check=True)
|
||||
logging.info("Pushing branch")
|
||||
subprocess.run(["git", "push", "origin", branch_name], check=True)
|
||||
logging.info("Creating PR")
|
||||
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
|
||||
logging.info(f"Created PR: {pr.number}")
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
coverage combine
|
||||
coverage report
|
||||
coverage html
|
||||
@@ -0,0 +1,149 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
from github import Auth, Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_repository: str
|
||||
github_token: SecretStr
|
||||
deploy_url: str | None = None
|
||||
commit_sha: str
|
||||
run_id: int
|
||||
state: Literal["pending", "success", "error"] = "pending"
|
||||
|
||||
|
||||
class LinkData(BaseModel):
|
||||
previous_link: str
|
||||
preview_link: str
|
||||
en_link: str | None = None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
|
||||
logging.info(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(auth=Auth.Token(settings.github_token.get_secret_value()))
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
use_pr = next(
|
||||
(pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None
|
||||
)
|
||||
if not use_pr:
|
||||
logging.error(f"No PR found for hash: {settings.commit_sha}")
|
||||
return
|
||||
commits = list(use_pr.get_commits())
|
||||
current_commit = [c for c in commits if c.sha == settings.commit_sha][0]
|
||||
run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}"
|
||||
if settings.state == "pending":
|
||||
current_commit.create_status(
|
||||
state="pending",
|
||||
description="Deploying Docs",
|
||||
context="deploy-docs",
|
||||
target_url=run_url,
|
||||
)
|
||||
logging.info("No deploy URL available yet")
|
||||
return
|
||||
if settings.state == "error":
|
||||
current_commit.create_status(
|
||||
state="error",
|
||||
description="Error Deploying Docs",
|
||||
context="deploy-docs",
|
||||
target_url=run_url,
|
||||
)
|
||||
logging.info("Error deploying docs")
|
||||
return
|
||||
assert settings.state == "success"
|
||||
if not settings.deploy_url:
|
||||
current_commit.create_status(
|
||||
state="success",
|
||||
description="No Docs Changes",
|
||||
context="deploy-docs",
|
||||
target_url=run_url,
|
||||
)
|
||||
logging.info("No docs changes found")
|
||||
return
|
||||
assert settings.deploy_url
|
||||
current_commit.create_status(
|
||||
state="success",
|
||||
description="Docs Deployed",
|
||||
context="deploy-docs",
|
||||
target_url=run_url,
|
||||
)
|
||||
|
||||
files = list(use_pr.get_files())
|
||||
docs_files = [f for f in files if f.filename.startswith("docs/")]
|
||||
|
||||
deploy_url = settings.deploy_url.rstrip("/")
|
||||
lang_links: dict[str, list[LinkData]] = {}
|
||||
for f in docs_files:
|
||||
match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename)
|
||||
if not match:
|
||||
continue
|
||||
lang = match.group(1)
|
||||
path = match.group(2)
|
||||
if path.endswith("index.md"):
|
||||
path = path.replace("index.md", "")
|
||||
else:
|
||||
path = path.replace(".md", "/")
|
||||
en_path = path
|
||||
if lang == "en":
|
||||
use_path = en_path
|
||||
else:
|
||||
use_path = f"{lang}/{path}"
|
||||
link = LinkData(
|
||||
previous_link=f"https://fastapi.tiangolo.com/{use_path}",
|
||||
preview_link=f"{deploy_url}/{use_path}",
|
||||
)
|
||||
if lang != "en":
|
||||
link.en_link = f"https://fastapi.tiangolo.com/{en_path}"
|
||||
lang_links.setdefault(lang, []).append(link)
|
||||
|
||||
links: list[LinkData] = []
|
||||
en_links = lang_links.get("en", [])
|
||||
en_links.sort(key=lambda x: x.preview_link)
|
||||
links.extend(en_links)
|
||||
|
||||
langs = list(lang_links.keys())
|
||||
langs.sort()
|
||||
for lang in langs:
|
||||
if lang == "en":
|
||||
continue
|
||||
current_lang_links = lang_links[lang]
|
||||
current_lang_links.sort(key=lambda x: x.preview_link)
|
||||
links.extend(current_lang_links)
|
||||
|
||||
header = "## 📝 Docs preview"
|
||||
message = header
|
||||
message += f"\n\nLast commit {settings.commit_sha} at: {deploy_url}"
|
||||
|
||||
if links:
|
||||
message += "\n\n### Modified Pages\n\n"
|
||||
for link in links:
|
||||
message += f"* {link.preview_link}"
|
||||
message += f" - ([before]({link.previous_link}))"
|
||||
if link.en_link:
|
||||
message += f" - ([English]({link.en_link}))"
|
||||
message += "\n"
|
||||
|
||||
print(message)
|
||||
issue = use_pr.as_issue()
|
||||
comments = list(issue.get_comments())
|
||||
for comment in comments:
|
||||
if (
|
||||
comment.body.startswith(header)
|
||||
and comment.user.login == "github-actions[bot]"
|
||||
):
|
||||
comment.edit(message)
|
||||
break
|
||||
else:
|
||||
issue.create_comment(message)
|
||||
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from html.parser import HTMLParser
|
||||
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
||||
from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
import mkdocs.utils
|
||||
import typer
|
||||
import yaml
|
||||
from jinja2 import Template
|
||||
from ruff.__main__ import find_ruff_bin
|
||||
from slugify import slugify as py_slugify
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
app = typer.Typer()
|
||||
|
||||
mkdocs_name = "mkdocs.yml"
|
||||
|
||||
missing_translation_snippet = """
|
||||
{!../../docs/missing-translation.md!}
|
||||
"""
|
||||
|
||||
non_translated_sections = (
|
||||
f"reference{os.sep}",
|
||||
"release-notes.md",
|
||||
"fastapi-people.md",
|
||||
"external-links.md",
|
||||
"newsletter.md",
|
||||
"management-tasks.md",
|
||||
"management.md",
|
||||
"contributing.md",
|
||||
)
|
||||
|
||||
docs_path = Path("docs")
|
||||
en_docs_path = Path("docs/en")
|
||||
en_config_path: Path = en_docs_path / mkdocs_name
|
||||
site_path = Path("site").absolute()
|
||||
build_site_path = Path("site_build").absolute()
|
||||
|
||||
header_pattern = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$")
|
||||
header_with_permalink_pattern = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})\s*$")
|
||||
code_block3_pattern = re.compile(r"^\s*```")
|
||||
code_block4_pattern = re.compile(r"^\s*````")
|
||||
|
||||
|
||||
class VisibleTextExtractor(HTMLParser):
|
||||
"""Extract visible text from a string with HTML tags."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.text_parts = []
|
||||
|
||||
def handle_data(self, data):
|
||||
self.text_parts.append(data)
|
||||
|
||||
def extract_visible_text(self, html: str) -> str:
|
||||
self.reset()
|
||||
self.text_parts = []
|
||||
self.feed(html)
|
||||
return "".join(self.text_parts).strip()
|
||||
|
||||
|
||||
def slugify(text: str) -> str:
|
||||
return py_slugify(
|
||||
text,
|
||||
replacements=[
|
||||
("`", ""), # `dict`s -> dicts
|
||||
("'s", "s"), # it's -> its
|
||||
("'t", "t"), # don't -> dont
|
||||
("**", ""), # **FastAPI**s -> FastAPIs
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def get_en_config() -> Dict[str, Any]:
|
||||
return mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def get_lang_paths() -> List[Path]:
|
||||
return sorted(docs_path.iterdir())
|
||||
|
||||
|
||||
def lang_callback(lang: Optional[str]) -> Union[str, None]:
|
||||
if lang is None:
|
||||
return None
|
||||
lang = lang.lower()
|
||||
return lang
|
||||
|
||||
|
||||
def complete_existing_lang(incomplete: str):
|
||||
lang_path: Path
|
||||
for lang_path in get_lang_paths():
|
||||
if lang_path.is_dir() and lang_path.name.startswith(incomplete):
|
||||
yield lang_path.name
|
||||
|
||||
|
||||
@app.callback()
|
||||
def callback() -> None:
|
||||
# For MacOS with Cairo
|
||||
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib"
|
||||
|
||||
|
||||
@app.command()
|
||||
def new_lang(lang: str = typer.Argument(..., callback=lang_callback)):
|
||||
"""
|
||||
Generate a new docs translation directory for the language LANG.
|
||||
"""
|
||||
new_path: Path = Path("docs") / lang
|
||||
if new_path.exists():
|
||||
typer.echo(f"The language was already created: {lang}")
|
||||
raise typer.Abort()
|
||||
new_path.mkdir()
|
||||
new_config_path: Path = Path(new_path) / mkdocs_name
|
||||
new_config_path.write_text("INHERIT: ../en/mkdocs.yml\n", encoding="utf-8")
|
||||
new_config_docs_path: Path = new_path / "docs"
|
||||
new_config_docs_path.mkdir()
|
||||
en_index_path: Path = en_docs_path / "docs" / "index.md"
|
||||
new_index_path: Path = new_config_docs_path / "index.md"
|
||||
en_index_content = en_index_path.read_text(encoding="utf-8")
|
||||
new_index_content = f"{missing_translation_snippet}\n\n{en_index_content}"
|
||||
new_index_path.write_text(new_index_content, encoding="utf-8")
|
||||
typer.secho(f"Successfully initialized: {new_path}", color=typer.colors.GREEN)
|
||||
update_languages()
|
||||
|
||||
|
||||
@app.command()
|
||||
def build_lang(
|
||||
lang: str = typer.Argument(
|
||||
..., callback=lang_callback, autocompletion=complete_existing_lang
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Build the docs for a language.
|
||||
"""
|
||||
lang_path: Path = Path("docs") / lang
|
||||
if not lang_path.is_dir():
|
||||
typer.echo(f"The language translation doesn't seem to exist yet: {lang}")
|
||||
raise typer.Abort()
|
||||
typer.echo(f"Building docs for: {lang}")
|
||||
build_site_dist_path = build_site_path / lang
|
||||
if lang == "en":
|
||||
dist_path = site_path
|
||||
# Don't remove en dist_path as it might already contain other languages.
|
||||
# When running build_all(), that function already removes site_path.
|
||||
# All this is only relevant locally, on GitHub Actions all this is done through
|
||||
# artifacts and multiple workflows, so it doesn't matter if directories are
|
||||
# removed or not.
|
||||
else:
|
||||
dist_path = site_path / lang
|
||||
shutil.rmtree(dist_path, ignore_errors=True)
|
||||
current_dir = os.getcwd()
|
||||
os.chdir(lang_path)
|
||||
shutil.rmtree(build_site_dist_path, ignore_errors=True)
|
||||
subprocess.run(["mkdocs", "build", "--site-dir", build_site_dist_path], check=True)
|
||||
shutil.copytree(build_site_dist_path, dist_path, dirs_exist_ok=True)
|
||||
os.chdir(current_dir)
|
||||
typer.secho(f"Successfully built docs for: {lang}", color=typer.colors.GREEN)
|
||||
|
||||
|
||||
index_sponsors_template = """
|
||||
### Keystone Sponsor
|
||||
|
||||
{% for sponsor in sponsors.keystone -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
|
||||
{% endfor %}
|
||||
### Gold and Silver Sponsors
|
||||
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
|
||||
{% endfor -%}
|
||||
{%- for sponsor in sponsors.silver -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
|
||||
{% endfor %}
|
||||
|
||||
"""
|
||||
|
||||
|
||||
def remove_header_permalinks(content: str):
|
||||
lines: list[str] = []
|
||||
for line in content.split("\n"):
|
||||
match = header_with_permalink_pattern.match(line)
|
||||
if match:
|
||||
hashes, title, *_ = match.groups()
|
||||
line = f"{hashes} {title}"
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_readme_content() -> str:
|
||||
en_index = en_docs_path / "docs" / "index.md"
|
||||
content = en_index.read_text("utf-8")
|
||||
content = remove_header_permalinks(content) # remove permalinks from headers
|
||||
match_pre = re.search(r"</style>\n\n", content)
|
||||
match_start = re.search(r"<!-- sponsors -->", content)
|
||||
match_end = re.search(r"<!-- /sponsors -->", content)
|
||||
sponsors_data_path = en_docs_path / "data" / "sponsors.yml"
|
||||
sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8"))
|
||||
if not (match_start and match_end):
|
||||
raise RuntimeError("Couldn't auto-generate sponsors section")
|
||||
if not match_pre:
|
||||
raise RuntimeError("Couldn't find pre section (<style>) in index.md")
|
||||
frontmatter_end = match_pre.end()
|
||||
pre_end = match_start.end()
|
||||
post_start = match_end.start()
|
||||
template = Template(index_sponsors_template)
|
||||
message = template.render(sponsors=sponsors)
|
||||
pre_content = content[frontmatter_end:pre_end]
|
||||
post_content = content[post_start:]
|
||||
new_content = pre_content + message + post_content
|
||||
# Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs -->
|
||||
new_content = re.sub(
|
||||
r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->",
|
||||
"",
|
||||
new_content,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
return new_content
|
||||
|
||||
|
||||
@app.command()
|
||||
def generate_readme() -> None:
|
||||
"""
|
||||
Generate README.md content from main index.md
|
||||
"""
|
||||
typer.echo("Generating README")
|
||||
readme_path = Path("README.md")
|
||||
new_content = generate_readme_content()
|
||||
readme_path.write_text(new_content, encoding="utf-8")
|
||||
|
||||
|
||||
@app.command()
|
||||
def verify_readme() -> None:
|
||||
"""
|
||||
Verify README.md content from main index.md
|
||||
"""
|
||||
typer.echo("Verifying README")
|
||||
readme_path = Path("README.md")
|
||||
generated_content = generate_readme_content()
|
||||
readme_content = readme_path.read_text("utf-8")
|
||||
if generated_content != readme_content:
|
||||
typer.secho(
|
||||
"README.md outdated from the latest index.md", color=typer.colors.RED
|
||||
)
|
||||
raise typer.Abort()
|
||||
typer.echo("Valid README ✅")
|
||||
|
||||
|
||||
@app.command()
|
||||
def build_all() -> None:
|
||||
"""
|
||||
Build mkdocs site for en, and then build each language inside, end result is located
|
||||
at directory ./site/ with each language inside.
|
||||
"""
|
||||
update_languages()
|
||||
shutil.rmtree(site_path, ignore_errors=True)
|
||||
langs = [lang.name for lang in get_lang_paths() if lang.is_dir()]
|
||||
cpu_count = os.cpu_count() or 1
|
||||
process_pool_size = cpu_count * 4
|
||||
typer.echo(f"Using process pool size: {process_pool_size}")
|
||||
with Pool(process_pool_size) as p:
|
||||
p.map(build_lang, langs)
|
||||
|
||||
|
||||
@app.command()
|
||||
def update_languages() -> None:
|
||||
"""
|
||||
Update the mkdocs.yml file Languages section including all the available languages.
|
||||
"""
|
||||
update_config()
|
||||
|
||||
|
||||
@app.command()
|
||||
def serve() -> None:
|
||||
"""
|
||||
A quick server to preview a built site with translations.
|
||||
|
||||
For development, prefer the command live (or just mkdocs serve).
|
||||
|
||||
This is here only to preview a site with translations already built.
|
||||
|
||||
Make sure you run the build-all command first.
|
||||
"""
|
||||
typer.echo("Warning: this is a very simple server.")
|
||||
typer.echo("For development, use the command live instead.")
|
||||
typer.echo("This is here only to preview a site with translations already built.")
|
||||
typer.echo("Make sure you run the build-all command first.")
|
||||
os.chdir("site")
|
||||
server_address = ("", 8008)
|
||||
server = HTTPServer(server_address, SimpleHTTPRequestHandler)
|
||||
typer.echo("Serving at: http://127.0.0.1:8008")
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
@app.command()
|
||||
def live(
|
||||
lang: str = typer.Argument(
|
||||
None, callback=lang_callback, autocompletion=complete_existing_lang
|
||||
),
|
||||
dirty: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Serve with livereload a docs site for a specific language.
|
||||
|
||||
This only shows the actual translated files, not the placeholders created with
|
||||
build-all.
|
||||
|
||||
Takes an optional LANG argument with the name of the language to serve, by default
|
||||
en.
|
||||
"""
|
||||
# Enable line numbers during local development to make it easier to highlight
|
||||
if lang is None:
|
||||
lang = "en"
|
||||
lang_path: Path = docs_path / lang
|
||||
# Enable line numbers during local development to make it easier to highlight
|
||||
args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"]
|
||||
if dirty:
|
||||
args.append("--dirty")
|
||||
subprocess.run(
|
||||
args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True
|
||||
)
|
||||
|
||||
|
||||
def get_updated_config_content() -> Dict[str, Any]:
|
||||
config = get_en_config()
|
||||
languages = [{"en": "/"}]
|
||||
new_alternate: List[Dict[str, str]] = []
|
||||
# Language names sourced from https://quickref.me/iso-639-1
|
||||
# Contributors may wish to update or change these, e.g. to fix capitalization.
|
||||
language_names_path = Path(__file__).parent / "../docs/language_names.yml"
|
||||
local_language_names: Dict[str, str] = mkdocs.utils.yaml_load(
|
||||
language_names_path.read_text(encoding="utf-8")
|
||||
)
|
||||
for lang_path in get_lang_paths():
|
||||
if lang_path.name in {"en", "em"} or not lang_path.is_dir():
|
||||
continue
|
||||
code = lang_path.name
|
||||
languages.append({code: f"/{code}/"})
|
||||
for lang_dict in languages:
|
||||
code = list(lang_dict.keys())[0]
|
||||
url = lang_dict[code]
|
||||
if code not in local_language_names:
|
||||
print(
|
||||
f"Missing language name for: {code}, "
|
||||
"update it in docs/language_names.yml"
|
||||
)
|
||||
raise typer.Abort()
|
||||
use_name = f"{code} - {local_language_names[code]}"
|
||||
new_alternate.append({"link": url, "name": use_name})
|
||||
new_alternate.append({"link": "/em/", "name": "😉"})
|
||||
config["extra"]["alternate"] = new_alternate
|
||||
return config
|
||||
|
||||
|
||||
def update_config() -> None:
|
||||
config = get_updated_config_content()
|
||||
en_config_path.write_text(
|
||||
yaml.dump(config, sort_keys=False, width=200, allow_unicode=True),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
@app.command()
|
||||
def verify_config() -> None:
|
||||
"""
|
||||
Verify main mkdocs.yml content to make sure it uses the latest language names.
|
||||
"""
|
||||
typer.echo("Verifying mkdocs.yml")
|
||||
config = get_en_config()
|
||||
updated_config = get_updated_config_content()
|
||||
if config != updated_config:
|
||||
typer.secho(
|
||||
"docs/en/mkdocs.yml outdated from docs/language_names.yml, "
|
||||
"update language_names.yml and run "
|
||||
"python ./scripts/docs.py update-languages",
|
||||
color=typer.colors.RED,
|
||||
)
|
||||
raise typer.Abort()
|
||||
typer.echo("Valid mkdocs.yml ✅")
|
||||
|
||||
|
||||
@app.command()
|
||||
def verify_non_translated() -> None:
|
||||
"""
|
||||
Verify there are no files in the non translatable pages.
|
||||
"""
|
||||
print("Verifying non translated pages")
|
||||
lang_paths = get_lang_paths()
|
||||
error_paths = []
|
||||
for lang in lang_paths:
|
||||
if lang.name == "en":
|
||||
continue
|
||||
for non_translatable in non_translated_sections:
|
||||
non_translatable_path = lang / "docs" / non_translatable
|
||||
if non_translatable_path.exists():
|
||||
error_paths.append(non_translatable_path)
|
||||
if error_paths:
|
||||
print("Non-translated pages found, remove them:")
|
||||
for error_path in error_paths:
|
||||
print(error_path)
|
||||
raise typer.Abort()
|
||||
print("No non-translated pages found ✅")
|
||||
|
||||
|
||||
@app.command()
|
||||
def verify_docs():
|
||||
verify_readme()
|
||||
verify_config()
|
||||
verify_non_translated()
|
||||
|
||||
|
||||
@app.command()
|
||||
def langs_json():
|
||||
langs = []
|
||||
for lang_path in get_lang_paths():
|
||||
if lang_path.is_dir():
|
||||
langs.append(lang_path.name)
|
||||
print(json.dumps(langs))
|
||||
|
||||
|
||||
@app.command()
|
||||
def generate_docs_src_versions_for_file(file_path: Path) -> None:
|
||||
target_versions = ["py39", "py310"]
|
||||
base_content = file_path.read_text(encoding="utf-8")
|
||||
previous_content = {base_content}
|
||||
for target_version in target_versions:
|
||||
version_result = subprocess.run(
|
||||
[
|
||||
find_ruff_bin(),
|
||||
"check",
|
||||
"--target-version",
|
||||
target_version,
|
||||
"--fix",
|
||||
"--unsafe-fixes",
|
||||
"-",
|
||||
],
|
||||
input=base_content.encode("utf-8"),
|
||||
capture_output=True,
|
||||
)
|
||||
content_target = version_result.stdout.decode("utf-8")
|
||||
format_result = subprocess.run(
|
||||
[find_ruff_bin(), "format", "-"],
|
||||
input=content_target.encode("utf-8"),
|
||||
capture_output=True,
|
||||
)
|
||||
content_format = format_result.stdout.decode("utf-8")
|
||||
if content_format in previous_content:
|
||||
continue
|
||||
previous_content.add(content_format)
|
||||
version_file = file_path.with_name(
|
||||
file_path.name.replace(".py", f"_{target_version}.py")
|
||||
)
|
||||
logging.info(f"Writing to {version_file}")
|
||||
version_file.write_text(content_format, encoding="utf-8")
|
||||
|
||||
|
||||
@app.command()
|
||||
def add_permalinks_page(path: Path, update_existing: bool = False):
|
||||
"""
|
||||
Add or update header permalinks in specific page of En docs.
|
||||
"""
|
||||
|
||||
if not path.is_relative_to(en_docs_path / "docs"):
|
||||
raise RuntimeError(f"Path must be inside {en_docs_path}")
|
||||
rel_path = path.relative_to(en_docs_path / "docs")
|
||||
|
||||
# Skip excluded sections
|
||||
if str(rel_path).startswith(non_translated_sections):
|
||||
return
|
||||
|
||||
visible_text_extractor = VisibleTextExtractor()
|
||||
updated_lines = []
|
||||
in_code_block3 = False
|
||||
in_code_block4 = False
|
||||
permalinks = set()
|
||||
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
for line in lines:
|
||||
# Handle codeblocks start and end
|
||||
if not (in_code_block3 or in_code_block4):
|
||||
if code_block4_pattern.match(line):
|
||||
in_code_block4 = True
|
||||
elif code_block3_pattern.match(line):
|
||||
in_code_block3 = True
|
||||
else:
|
||||
if in_code_block4 and code_block4_pattern.match(line):
|
||||
in_code_block4 = False
|
||||
elif in_code_block3 and code_block3_pattern.match(line):
|
||||
in_code_block3 = False
|
||||
|
||||
# Process Headers only outside codeblocks
|
||||
if not (in_code_block3 or in_code_block4):
|
||||
match = header_pattern.match(line)
|
||||
if match:
|
||||
hashes, title, _permalink = match.groups()
|
||||
if (not _permalink) or update_existing:
|
||||
slug = slugify(visible_text_extractor.extract_visible_text(title))
|
||||
if slug in permalinks:
|
||||
# If the slug is already used, append a number to make it unique
|
||||
count = 1
|
||||
original_slug = slug
|
||||
while slug in permalinks:
|
||||
slug = f"{original_slug}_{count}"
|
||||
count += 1
|
||||
permalinks.add(slug)
|
||||
|
||||
line = f"{hashes} {title} {{ #{slug} }}\n"
|
||||
|
||||
updated_lines.append(line)
|
||||
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
f.writelines(updated_lines)
|
||||
|
||||
|
||||
@app.command()
|
||||
def add_permalinks_pages(pages: List[Path], update_existing: bool = False) -> None:
|
||||
"""
|
||||
Add or update header permalinks in specific pages of En docs.
|
||||
"""
|
||||
for md_file in pages:
|
||||
add_permalinks_page(md_file, update_existing=update_existing)
|
||||
|
||||
|
||||
@app.command()
|
||||
def add_permalinks(update_existing: bool = False) -> None:
|
||||
"""
|
||||
Add or update header permalinks in all pages of En docs.
|
||||
"""
|
||||
for md_file in en_docs_path.rglob("*.md"):
|
||||
add_permalinks_page(md_file, update_existing=update_existing)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -x
|
||||
|
||||
ruff check fastapi tests docs_src scripts --fix
|
||||
ruff format fastapi tests docs_src scripts
|
||||
@@ -0,0 +1,60 @@
|
||||
import logging
|
||||
from typing import Literal
|
||||
|
||||
from github import Github
|
||||
from github.PullRequestReview import PullRequestReview
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class LabelSettings(BaseModel):
|
||||
await_label: str | None = None
|
||||
number: int
|
||||
|
||||
|
||||
default_config = {"approved-2": LabelSettings(await_label="awaiting-review", number=2)}
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_repository: str
|
||||
token: SecretStr
|
||||
debug: bool | None = False
|
||||
config: dict[str, LabelSettings] | Literal[""] = default_config
|
||||
|
||||
|
||||
settings = Settings()
|
||||
if settings.debug:
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
else:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.debug(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
for pr in repo.get_pulls(state="open"):
|
||||
logging.info(f"Checking PR: #{pr.number}")
|
||||
pr_labels = list(pr.get_labels())
|
||||
pr_label_by_name = {label.name: label for label in pr_labels}
|
||||
reviews = list(pr.get_reviews())
|
||||
review_by_user: dict[str, PullRequestReview] = {}
|
||||
for review in reviews:
|
||||
if review.user.login in review_by_user:
|
||||
stored_review = review_by_user[review.user.login]
|
||||
if review.submitted_at >= stored_review.submitted_at:
|
||||
review_by_user[review.user.login] = review
|
||||
else:
|
||||
review_by_user[review.user.login] = review
|
||||
approved_reviews = [
|
||||
review for review in review_by_user.values() if review.state == "APPROVED"
|
||||
]
|
||||
config = settings.config or default_config
|
||||
for approved_label, conf in config.items():
|
||||
logging.debug(f"Processing config: {conf.model_dump_json()}")
|
||||
if conf.await_label is None or (conf.await_label in pr_label_by_name):
|
||||
logging.debug(f"Processable PR: {pr.number}")
|
||||
if len(approved_reviews) >= conf.number:
|
||||
logging.info(f"Adding label to PR: {pr.number}")
|
||||
pr.add_to_labels(approved_label)
|
||||
if conf.await_label:
|
||||
logging.info(f"Removing label from PR: {pr.number}")
|
||||
pr.remove_from_labels(conf.await_label)
|
||||
logging.info("Finished")
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
mypy fastapi
|
||||
ruff check fastapi tests docs_src scripts
|
||||
ruff format fastapi tests --check
|
||||
@@ -0,0 +1,154 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Union
|
||||
|
||||
import material
|
||||
from mkdocs.config.defaults import MkDocsConfig
|
||||
from mkdocs.structure.files import File, Files
|
||||
from mkdocs.structure.nav import Link, Navigation, Section
|
||||
from mkdocs.structure.pages import Page
|
||||
|
||||
non_translated_sections = [
|
||||
"reference/",
|
||||
"release-notes.md",
|
||||
"fastapi-people.md",
|
||||
"external-links.md",
|
||||
"newsletter.md",
|
||||
"management-tasks.md",
|
||||
"management.md",
|
||||
]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_missing_translation_content(docs_dir: str) -> str:
|
||||
docs_dir_path = Path(docs_dir)
|
||||
missing_translation_path = docs_dir_path.parent.parent / "missing-translation.md"
|
||||
return missing_translation_path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_mkdocs_material_langs() -> List[str]:
|
||||
material_path = Path(material.__file__).parent
|
||||
material_langs_path = material_path / "templates" / "partials" / "languages"
|
||||
langs = [file.stem for file in material_langs_path.glob("*.html")]
|
||||
return langs
|
||||
|
||||
|
||||
class EnFile(File):
|
||||
pass
|
||||
|
||||
|
||||
def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig:
|
||||
available_langs = get_mkdocs_material_langs()
|
||||
dir_path = Path(config.docs_dir)
|
||||
lang = dir_path.parent.name
|
||||
if lang in available_langs:
|
||||
config.theme["language"] = lang
|
||||
if not (config.site_url or "").endswith(f"{lang}/") and lang != "en":
|
||||
config.site_url = f"{config.site_url}{lang}/"
|
||||
return config
|
||||
|
||||
|
||||
def resolve_file(*, item: str, files: Files, config: MkDocsConfig) -> None:
|
||||
item_path = Path(config.docs_dir) / item
|
||||
if not item_path.is_file():
|
||||
en_src_dir = (Path(config.docs_dir) / "../../en/docs").resolve()
|
||||
potential_path = en_src_dir / item
|
||||
if potential_path.is_file():
|
||||
files.append(
|
||||
EnFile(
|
||||
path=item,
|
||||
src_dir=str(en_src_dir),
|
||||
dest_dir=config.site_dir,
|
||||
use_directory_urls=config.use_directory_urls,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def resolve_files(*, items: List[Any], files: Files, config: MkDocsConfig) -> None:
|
||||
for item in items:
|
||||
if isinstance(item, str):
|
||||
resolve_file(item=item, files=files, config=config)
|
||||
elif isinstance(item, dict):
|
||||
assert len(item) == 1
|
||||
values = list(item.values())
|
||||
if not values:
|
||||
continue
|
||||
if isinstance(values[0], str):
|
||||
resolve_file(item=values[0], files=files, config=config)
|
||||
elif isinstance(values[0], list):
|
||||
resolve_files(items=values[0], files=files, config=config)
|
||||
else:
|
||||
raise ValueError(f"Unexpected value: {values}")
|
||||
|
||||
|
||||
def on_files(files: Files, *, config: MkDocsConfig) -> Files:
|
||||
resolve_files(items=config.nav or [], files=files, config=config)
|
||||
if "logo" in config.theme:
|
||||
resolve_file(item=config.theme["logo"], files=files, config=config)
|
||||
if "favicon" in config.theme:
|
||||
resolve_file(item=config.theme["favicon"], files=files, config=config)
|
||||
resolve_files(items=config.extra_css, files=files, config=config)
|
||||
resolve_files(items=config.extra_javascript, files=files, config=config)
|
||||
return files
|
||||
|
||||
|
||||
def generate_renamed_section_items(
|
||||
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
|
||||
) -> List[Union[Page, Section, Link]]:
|
||||
new_items: List[Union[Page, Section, Link]] = []
|
||||
for item in items:
|
||||
if isinstance(item, Section):
|
||||
new_title = item.title
|
||||
new_children = generate_renamed_section_items(item.children, config=config)
|
||||
first_child = new_children[0]
|
||||
if isinstance(first_child, Page):
|
||||
if first_child.file.src_path.endswith("index.md"):
|
||||
# Read the source so that the title is parsed and available
|
||||
first_child.read_source(config=config)
|
||||
new_title = first_child.title or new_title
|
||||
# Creating a new section makes it render it collapsed by default
|
||||
# no idea why, so, let's just modify the existing one
|
||||
# new_section = Section(title=new_title, children=new_children)
|
||||
item.title = new_title.split("{ #")[0]
|
||||
item.children = new_children
|
||||
new_items.append(item)
|
||||
else:
|
||||
new_items.append(item)
|
||||
return new_items
|
||||
|
||||
|
||||
def on_nav(
|
||||
nav: Navigation, *, config: MkDocsConfig, files: Files, **kwargs: Any
|
||||
) -> Navigation:
|
||||
new_items = generate_renamed_section_items(nav.items, config=config)
|
||||
return Navigation(items=new_items, pages=nav.pages)
|
||||
|
||||
|
||||
def on_pre_page(page: Page, *, config: MkDocsConfig, files: Files) -> Page:
|
||||
return page
|
||||
|
||||
|
||||
def on_page_markdown(
|
||||
markdown: str, *, page: Page, config: MkDocsConfig, files: Files
|
||||
) -> str:
|
||||
# Set metadata["social"]["cards_layout_options"]["title"] to clean title (without
|
||||
# permalink)
|
||||
title = page.title
|
||||
clean_title = title.split("{ #")[0]
|
||||
if clean_title:
|
||||
page.meta.setdefault("social", {})
|
||||
page.meta["social"].setdefault("cards_layout_options", {})
|
||||
page.meta["social"]["cards_layout_options"]["title"] = clean_title
|
||||
|
||||
if isinstance(page.file, EnFile):
|
||||
for excluded_section in non_translated_sections:
|
||||
if page.file.src_path.startswith(excluded_section):
|
||||
return markdown
|
||||
missing_translation_content = get_missing_translation_content(config.docs_dir)
|
||||
header = ""
|
||||
body = markdown
|
||||
if markdown.startswith("#"):
|
||||
header, _, body = markdown.partition("\n\n")
|
||||
return f"{header}\n\n{missing_translation_content}\n\n{body}"
|
||||
return markdown
|
||||
@@ -0,0 +1,432 @@
|
||||
import logging
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Union, cast
|
||||
|
||||
import httpx
|
||||
from github import Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
awaiting_label = "awaiting-review"
|
||||
lang_all_label = "lang-all"
|
||||
approved_label = "approved-1"
|
||||
|
||||
|
||||
github_graphql_url = "https://api.github.com/graphql"
|
||||
questions_translations_category_id = "DIC_kwDOCZduT84CT5P9"
|
||||
|
||||
all_discussions_query = """
|
||||
query Q($category_id: ID) {
|
||||
repository(name: "fastapi", owner: "fastapi") {
|
||||
discussions(categoryId: $category_id, first: 100) {
|
||||
nodes {
|
||||
title
|
||||
id
|
||||
number
|
||||
labels(first: 10) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
translation_discussion_query = """
|
||||
query Q($after: String, $discussion_number: Int!) {
|
||||
repository(name: "fastapi", owner: "fastapi") {
|
||||
discussion(number: $discussion_number) {
|
||||
comments(first: 100, after: $after) {
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
id
|
||||
url
|
||||
body
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
add_comment_mutation = """
|
||||
mutation Q($discussion_id: ID!, $body: String!) {
|
||||
addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) {
|
||||
comment {
|
||||
id
|
||||
url
|
||||
body
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
update_comment_mutation = """
|
||||
mutation Q($comment_id: ID!, $body: String!) {
|
||||
updateDiscussionComment(input: {commentId: $comment_id, body: $body}) {
|
||||
comment {
|
||||
id
|
||||
url
|
||||
body
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class Comment(BaseModel):
|
||||
id: str
|
||||
url: str
|
||||
body: str
|
||||
|
||||
|
||||
class UpdateDiscussionComment(BaseModel):
|
||||
comment: Comment
|
||||
|
||||
|
||||
class UpdateCommentData(BaseModel):
|
||||
updateDiscussionComment: UpdateDiscussionComment
|
||||
|
||||
|
||||
class UpdateCommentResponse(BaseModel):
|
||||
data: UpdateCommentData
|
||||
|
||||
|
||||
class AddDiscussionComment(BaseModel):
|
||||
comment: Comment
|
||||
|
||||
|
||||
class AddCommentData(BaseModel):
|
||||
addDiscussionComment: AddDiscussionComment
|
||||
|
||||
|
||||
class AddCommentResponse(BaseModel):
|
||||
data: AddCommentData
|
||||
|
||||
|
||||
class CommentsEdge(BaseModel):
|
||||
node: Comment
|
||||
cursor: str
|
||||
|
||||
|
||||
class Comments(BaseModel):
|
||||
edges: List[CommentsEdge]
|
||||
|
||||
|
||||
class CommentsDiscussion(BaseModel):
|
||||
comments: Comments
|
||||
|
||||
|
||||
class CommentsRepository(BaseModel):
|
||||
discussion: CommentsDiscussion
|
||||
|
||||
|
||||
class CommentsData(BaseModel):
|
||||
repository: CommentsRepository
|
||||
|
||||
|
||||
class CommentsResponse(BaseModel):
|
||||
data: CommentsData
|
||||
|
||||
|
||||
class AllDiscussionsLabelNode(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
|
||||
|
||||
class AllDiscussionsLabelsEdge(BaseModel):
|
||||
node: AllDiscussionsLabelNode
|
||||
|
||||
|
||||
class AllDiscussionsDiscussionLabels(BaseModel):
|
||||
edges: List[AllDiscussionsLabelsEdge]
|
||||
|
||||
|
||||
class AllDiscussionsDiscussionNode(BaseModel):
|
||||
title: str
|
||||
id: str
|
||||
number: int
|
||||
labels: AllDiscussionsDiscussionLabels
|
||||
|
||||
|
||||
class AllDiscussionsDiscussions(BaseModel):
|
||||
nodes: List[AllDiscussionsDiscussionNode]
|
||||
|
||||
|
||||
class AllDiscussionsRepository(BaseModel):
|
||||
discussions: AllDiscussionsDiscussions
|
||||
|
||||
|
||||
class AllDiscussionsData(BaseModel):
|
||||
repository: AllDiscussionsRepository
|
||||
|
||||
|
||||
class AllDiscussionsResponse(BaseModel):
|
||||
data: AllDiscussionsData
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = {"env_ignore_empty": True}
|
||||
|
||||
github_repository: str
|
||||
github_token: SecretStr
|
||||
github_event_path: Path
|
||||
github_event_name: Union[str, None] = None
|
||||
httpx_timeout: int = 30
|
||||
debug: Union[bool, None] = False
|
||||
number: int | None = None
|
||||
|
||||
|
||||
class PartialGitHubEventIssue(BaseModel):
|
||||
number: int | None = None
|
||||
|
||||
|
||||
class PartialGitHubEvent(BaseModel):
|
||||
pull_request: PartialGitHubEventIssue | None = None
|
||||
|
||||
|
||||
def get_graphql_response(
|
||||
*,
|
||||
settings: Settings,
|
||||
query: str,
|
||||
after: Union[str, None] = None,
|
||||
category_id: Union[str, None] = None,
|
||||
discussion_number: Union[int, None] = None,
|
||||
discussion_id: Union[str, None] = None,
|
||||
comment_id: Union[str, None] = None,
|
||||
body: Union[str, None] = None,
|
||||
) -> Dict[str, Any]:
|
||||
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
|
||||
variables = {
|
||||
"after": after,
|
||||
"category_id": category_id,
|
||||
"discussion_number": discussion_number,
|
||||
"discussion_id": discussion_id,
|
||||
"comment_id": comment_id,
|
||||
"body": body,
|
||||
}
|
||||
response = httpx.post(
|
||||
github_graphql_url,
|
||||
headers=headers,
|
||||
timeout=settings.httpx_timeout,
|
||||
json={"query": query, "variables": variables, "operationName": "Q"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
logging.error(
|
||||
f"Response was not 200, after: {after}, category_id: {category_id}"
|
||||
)
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
data = response.json()
|
||||
if "errors" in data:
|
||||
logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
|
||||
logging.error(data["errors"])
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
return cast(Dict[str, Any], data)
|
||||
|
||||
|
||||
def get_graphql_translation_discussions(
|
||||
*, settings: Settings
|
||||
) -> List[AllDiscussionsDiscussionNode]:
|
||||
data = get_graphql_response(
|
||||
settings=settings,
|
||||
query=all_discussions_query,
|
||||
category_id=questions_translations_category_id,
|
||||
)
|
||||
graphql_response = AllDiscussionsResponse.model_validate(data)
|
||||
return graphql_response.data.repository.discussions.nodes
|
||||
|
||||
|
||||
def get_graphql_translation_discussion_comments_edges(
|
||||
*, settings: Settings, discussion_number: int, after: Union[str, None] = None
|
||||
) -> List[CommentsEdge]:
|
||||
data = get_graphql_response(
|
||||
settings=settings,
|
||||
query=translation_discussion_query,
|
||||
discussion_number=discussion_number,
|
||||
after=after,
|
||||
)
|
||||
graphql_response = CommentsResponse.model_validate(data)
|
||||
return graphql_response.data.repository.discussion.comments.edges
|
||||
|
||||
|
||||
def get_graphql_translation_discussion_comments(
|
||||
*, settings: Settings, discussion_number: int
|
||||
) -> list[Comment]:
|
||||
comment_nodes: List[Comment] = []
|
||||
discussion_edges = get_graphql_translation_discussion_comments_edges(
|
||||
settings=settings, discussion_number=discussion_number
|
||||
)
|
||||
|
||||
while discussion_edges:
|
||||
for discussion_edge in discussion_edges:
|
||||
comment_nodes.append(discussion_edge.node)
|
||||
last_edge = discussion_edges[-1]
|
||||
discussion_edges = get_graphql_translation_discussion_comments_edges(
|
||||
settings=settings,
|
||||
discussion_number=discussion_number,
|
||||
after=last_edge.cursor,
|
||||
)
|
||||
return comment_nodes
|
||||
|
||||
|
||||
def create_comment(*, settings: Settings, discussion_id: str, body: str) -> Comment:
|
||||
data = get_graphql_response(
|
||||
settings=settings,
|
||||
query=add_comment_mutation,
|
||||
discussion_id=discussion_id,
|
||||
body=body,
|
||||
)
|
||||
response = AddCommentResponse.model_validate(data)
|
||||
return response.data.addDiscussionComment.comment
|
||||
|
||||
|
||||
def update_comment(*, settings: Settings, comment_id: str, body: str) -> Comment:
|
||||
data = get_graphql_response(
|
||||
settings=settings,
|
||||
query=update_comment_mutation,
|
||||
comment_id=comment_id,
|
||||
body=body,
|
||||
)
|
||||
response = UpdateCommentResponse.model_validate(data)
|
||||
return response.data.updateDiscussionComment.comment
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = Settings()
|
||||
if settings.debug:
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
else:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.debug(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.github_token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
if not settings.github_event_path.is_file():
|
||||
raise RuntimeError(
|
||||
f"No github event file available at: {settings.github_event_path}"
|
||||
)
|
||||
contents = settings.github_event_path.read_text()
|
||||
github_event = PartialGitHubEvent.model_validate_json(contents)
|
||||
logging.info(f"Using GitHub event: {github_event}")
|
||||
number = (
|
||||
github_event.pull_request and github_event.pull_request.number
|
||||
) or settings.number
|
||||
if number is None:
|
||||
raise RuntimeError("No PR number available")
|
||||
|
||||
# Avoid race conditions with multiple labels
|
||||
sleep_time = random.random() * 10 # random number between 0 and 10 seconds
|
||||
logging.info(
|
||||
f"Sleeping for {sleep_time} seconds to avoid "
|
||||
"race conditions and multiple comments"
|
||||
)
|
||||
time.sleep(sleep_time)
|
||||
|
||||
# Get PR
|
||||
logging.debug(f"Processing PR: #{number}")
|
||||
pr = repo.get_pull(number)
|
||||
label_strs = {label.name for label in pr.get_labels()}
|
||||
langs = []
|
||||
for label in label_strs:
|
||||
if label.startswith("lang-") and not label == lang_all_label:
|
||||
langs.append(label[5:])
|
||||
logging.info(f"PR #{pr.number} has labels: {label_strs}")
|
||||
if not langs or lang_all_label not in label_strs:
|
||||
logging.info(f"PR #{pr.number} doesn't seem to be a translation PR, skipping")
|
||||
sys.exit(0)
|
||||
|
||||
# Generate translation map, lang ID to discussion
|
||||
discussions = get_graphql_translation_discussions(settings=settings)
|
||||
lang_to_discussion_map: Dict[str, AllDiscussionsDiscussionNode] = {}
|
||||
for discussion in discussions:
|
||||
for edge in discussion.labels.edges:
|
||||
label = edge.node.name
|
||||
if label.startswith("lang-") and not label == lang_all_label:
|
||||
lang = label[5:]
|
||||
lang_to_discussion_map[lang] = discussion
|
||||
logging.debug(f"Using translations map: {lang_to_discussion_map}")
|
||||
|
||||
# Messages to create or check
|
||||
new_translation_message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓"
|
||||
done_translation_message = f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕"
|
||||
|
||||
# Normally only one language, but still
|
||||
for lang in langs:
|
||||
if lang not in lang_to_discussion_map:
|
||||
log_message = f"Could not find discussion for language: {lang}"
|
||||
logging.error(log_message)
|
||||
raise RuntimeError(log_message)
|
||||
discussion = lang_to_discussion_map[lang]
|
||||
logging.info(
|
||||
f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}"
|
||||
)
|
||||
|
||||
already_notified_comment: Union[Comment, None] = None
|
||||
already_done_comment: Union[Comment, None] = None
|
||||
|
||||
logging.info(
|
||||
f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}"
|
||||
)
|
||||
comments = get_graphql_translation_discussion_comments(
|
||||
settings=settings, discussion_number=discussion.number
|
||||
)
|
||||
for comment in comments:
|
||||
if new_translation_message in comment.body:
|
||||
already_notified_comment = comment
|
||||
elif done_translation_message in comment.body:
|
||||
already_done_comment = comment
|
||||
logging.info(
|
||||
f"Already notified comment: {already_notified_comment}, already done comment: {already_done_comment}"
|
||||
)
|
||||
|
||||
if pr.state == "open" and awaiting_label in label_strs:
|
||||
logging.info(
|
||||
f"This PR seems to be a language translation and awaiting reviews: #{pr.number}"
|
||||
)
|
||||
if already_notified_comment:
|
||||
logging.info(
|
||||
f"This PR #{pr.number} was already notified in comment: {already_notified_comment.url}"
|
||||
)
|
||||
else:
|
||||
logging.info(
|
||||
f"Writing notification comment about PR #{pr.number} in Discussion: #{discussion.number}"
|
||||
)
|
||||
comment = create_comment(
|
||||
settings=settings,
|
||||
discussion_id=discussion.id,
|
||||
body=new_translation_message,
|
||||
)
|
||||
logging.info(f"Notified in comment: {comment.url}")
|
||||
elif pr.state == "closed" or approved_label in label_strs:
|
||||
logging.info(f"Already approved or closed PR #{pr.number}")
|
||||
if already_done_comment:
|
||||
logging.info(
|
||||
f"This PR #{pr.number} was already marked as done in comment: {already_done_comment.url}"
|
||||
)
|
||||
elif already_notified_comment:
|
||||
updated_comment = update_comment(
|
||||
settings=settings,
|
||||
comment_id=already_notified_comment.id,
|
||||
body=done_translation_message,
|
||||
)
|
||||
logging.info(f"Marked as done in comment: {updated_comment.url}")
|
||||
else:
|
||||
logging.info(
|
||||
f"There doesn't seem to be anything to be done about PR #{pr.number}"
|
||||
)
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,402 @@
|
||||
import logging
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Container, Union
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from github import Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
github_graphql_url = "https://api.github.com/graphql"
|
||||
questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0"
|
||||
|
||||
discussions_query = """
|
||||
query Q($after: String, $category_id: ID) {
|
||||
repository(name: "fastapi", owner: "fastapi") {
|
||||
discussions(first: 100, after: $after, categoryId: $category_id) {
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
number
|
||||
author {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
createdAt
|
||||
comments(first: 50) {
|
||||
totalCount
|
||||
nodes {
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
isAnswer
|
||||
replies(first: 10) {
|
||||
totalCount
|
||||
nodes {
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class Author(BaseModel):
|
||||
login: str
|
||||
avatarUrl: str | None = None
|
||||
url: str | None = None
|
||||
|
||||
|
||||
class CommentsNode(BaseModel):
|
||||
createdAt: datetime
|
||||
author: Union[Author, None] = None
|
||||
|
||||
|
||||
class Replies(BaseModel):
|
||||
totalCount: int
|
||||
nodes: list[CommentsNode]
|
||||
|
||||
|
||||
class DiscussionsCommentsNode(CommentsNode):
|
||||
replies: Replies
|
||||
|
||||
|
||||
class DiscussionsComments(BaseModel):
|
||||
totalCount: int
|
||||
nodes: list[DiscussionsCommentsNode]
|
||||
|
||||
|
||||
class DiscussionsNode(BaseModel):
|
||||
number: int
|
||||
author: Union[Author, None] = None
|
||||
title: str | None = None
|
||||
createdAt: datetime
|
||||
comments: DiscussionsComments
|
||||
|
||||
|
||||
class DiscussionsEdge(BaseModel):
|
||||
cursor: str
|
||||
node: DiscussionsNode
|
||||
|
||||
|
||||
class Discussions(BaseModel):
|
||||
edges: list[DiscussionsEdge]
|
||||
|
||||
|
||||
class DiscussionsRepository(BaseModel):
|
||||
discussions: Discussions
|
||||
|
||||
|
||||
class DiscussionsResponseData(BaseModel):
|
||||
repository: DiscussionsRepository
|
||||
|
||||
|
||||
class DiscussionsResponse(BaseModel):
|
||||
data: DiscussionsResponseData
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_token: SecretStr
|
||||
github_repository: str
|
||||
httpx_timeout: int = 30
|
||||
sleep_interval: int = 5
|
||||
|
||||
|
||||
def get_graphql_response(
|
||||
*,
|
||||
settings: Settings,
|
||||
query: str,
|
||||
after: Union[str, None] = None,
|
||||
category_id: Union[str, None] = None,
|
||||
) -> dict[str, Any]:
|
||||
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
|
||||
variables = {"after": after, "category_id": category_id}
|
||||
response = httpx.post(
|
||||
github_graphql_url,
|
||||
headers=headers,
|
||||
timeout=settings.httpx_timeout,
|
||||
json={"query": query, "variables": variables, "operationName": "Q"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
logging.error(
|
||||
f"Response was not 200, after: {after}, category_id: {category_id}"
|
||||
)
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
data = response.json()
|
||||
if "errors" in data:
|
||||
logging.error(f"Errors in response, after: {after}, category_id: {category_id}")
|
||||
logging.error(data["errors"])
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
return data
|
||||
|
||||
|
||||
def get_graphql_question_discussion_edges(
|
||||
*,
|
||||
settings: Settings,
|
||||
after: Union[str, None] = None,
|
||||
) -> list[DiscussionsEdge]:
|
||||
data = get_graphql_response(
|
||||
settings=settings,
|
||||
query=discussions_query,
|
||||
after=after,
|
||||
category_id=questions_category_id,
|
||||
)
|
||||
graphql_response = DiscussionsResponse.model_validate(data)
|
||||
return graphql_response.data.repository.discussions.edges
|
||||
|
||||
|
||||
class DiscussionExpertsResults(BaseModel):
|
||||
commenters: Counter[str]
|
||||
last_month_commenters: Counter[str]
|
||||
three_months_commenters: Counter[str]
|
||||
six_months_commenters: Counter[str]
|
||||
one_year_commenters: Counter[str]
|
||||
authors: dict[str, Author]
|
||||
|
||||
|
||||
def get_discussion_nodes(settings: Settings) -> list[DiscussionsNode]:
|
||||
discussion_nodes: list[DiscussionsNode] = []
|
||||
discussion_edges = get_graphql_question_discussion_edges(settings=settings)
|
||||
|
||||
while discussion_edges:
|
||||
for discussion_edge in discussion_edges:
|
||||
discussion_nodes.append(discussion_edge.node)
|
||||
last_edge = discussion_edges[-1]
|
||||
# Handle GitHub secondary rate limits, requests per minute
|
||||
time.sleep(settings.sleep_interval)
|
||||
discussion_edges = get_graphql_question_discussion_edges(
|
||||
settings=settings, after=last_edge.cursor
|
||||
)
|
||||
return discussion_nodes
|
||||
|
||||
|
||||
def get_discussions_experts(
|
||||
discussion_nodes: list[DiscussionsNode],
|
||||
) -> DiscussionExpertsResults:
|
||||
commenters = Counter[str]()
|
||||
last_month_commenters = Counter[str]()
|
||||
three_months_commenters = Counter[str]()
|
||||
six_months_commenters = Counter[str]()
|
||||
one_year_commenters = Counter[str]()
|
||||
authors: dict[str, Author] = {}
|
||||
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
one_month_ago = now - timedelta(days=30)
|
||||
three_months_ago = now - timedelta(days=90)
|
||||
six_months_ago = now - timedelta(days=180)
|
||||
one_year_ago = now - timedelta(days=365)
|
||||
|
||||
for discussion in discussion_nodes:
|
||||
discussion_author_name = None
|
||||
if discussion.author:
|
||||
authors[discussion.author.login] = discussion.author
|
||||
discussion_author_name = discussion.author.login
|
||||
discussion_commentors: dict[str, datetime] = {}
|
||||
for comment in discussion.comments.nodes:
|
||||
if comment.author:
|
||||
authors[comment.author.login] = comment.author
|
||||
if comment.author.login != discussion_author_name:
|
||||
author_time = discussion_commentors.get(
|
||||
comment.author.login, comment.createdAt
|
||||
)
|
||||
discussion_commentors[comment.author.login] = max(
|
||||
author_time, comment.createdAt
|
||||
)
|
||||
for reply in comment.replies.nodes:
|
||||
if reply.author:
|
||||
authors[reply.author.login] = reply.author
|
||||
if reply.author.login != discussion_author_name:
|
||||
author_time = discussion_commentors.get(
|
||||
reply.author.login, reply.createdAt
|
||||
)
|
||||
discussion_commentors[reply.author.login] = max(
|
||||
author_time, reply.createdAt
|
||||
)
|
||||
for author_name, author_time in discussion_commentors.items():
|
||||
commenters[author_name] += 1
|
||||
if author_time > one_month_ago:
|
||||
last_month_commenters[author_name] += 1
|
||||
if author_time > three_months_ago:
|
||||
three_months_commenters[author_name] += 1
|
||||
if author_time > six_months_ago:
|
||||
six_months_commenters[author_name] += 1
|
||||
if author_time > one_year_ago:
|
||||
one_year_commenters[author_name] += 1
|
||||
discussion_experts_results = DiscussionExpertsResults(
|
||||
authors=authors,
|
||||
commenters=commenters,
|
||||
last_month_commenters=last_month_commenters,
|
||||
three_months_commenters=three_months_commenters,
|
||||
six_months_commenters=six_months_commenters,
|
||||
one_year_commenters=one_year_commenters,
|
||||
)
|
||||
return discussion_experts_results
|
||||
|
||||
|
||||
def get_top_users(
|
||||
*,
|
||||
counter: Counter[str],
|
||||
authors: dict[str, Author],
|
||||
skip_users: Container[str],
|
||||
min_count: int = 2,
|
||||
) -> list[dict[str, Any]]:
|
||||
users: list[dict[str, Any]] = []
|
||||
for commenter, count in counter.most_common(50):
|
||||
if commenter in skip_users:
|
||||
continue
|
||||
if count >= min_count:
|
||||
author = authors[commenter]
|
||||
users.append(
|
||||
{
|
||||
"login": commenter,
|
||||
"count": count,
|
||||
"avatarUrl": author.avatarUrl,
|
||||
"url": author.url,
|
||||
}
|
||||
)
|
||||
return users
|
||||
|
||||
|
||||
def get_users_to_write(
|
||||
*,
|
||||
counter: Counter[str],
|
||||
authors: dict[str, Author],
|
||||
min_count: int = 2,
|
||||
) -> list[dict[str, Any]]:
|
||||
users: dict[str, Any] = {}
|
||||
users_list: list[dict[str, Any]] = []
|
||||
for user, count in counter.most_common(60):
|
||||
if count >= min_count:
|
||||
author = authors[user]
|
||||
user_data = {
|
||||
"login": user,
|
||||
"count": count,
|
||||
"avatarUrl": author.avatarUrl,
|
||||
"url": author.url,
|
||||
}
|
||||
users[user] = user_data
|
||||
users_list.append(user_data)
|
||||
return users_list
|
||||
|
||||
|
||||
def update_content(*, content_path: Path, new_content: Any) -> bool:
|
||||
old_content = content_path.read_text(encoding="utf-8")
|
||||
|
||||
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
|
||||
if old_content == new_content:
|
||||
logging.info(f"The content hasn't changed for {content_path}")
|
||||
return False
|
||||
content_path.write_text(new_content, encoding="utf-8")
|
||||
logging.info(f"Updated {content_path}")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
logging.info(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.github_token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
|
||||
discussion_nodes = get_discussion_nodes(settings=settings)
|
||||
experts_results = get_discussions_experts(discussion_nodes=discussion_nodes)
|
||||
|
||||
authors = experts_results.authors
|
||||
maintainers_logins = {"tiangolo"}
|
||||
maintainers = []
|
||||
for login in maintainers_logins:
|
||||
user = authors[login]
|
||||
maintainers.append(
|
||||
{
|
||||
"login": login,
|
||||
"answers": experts_results.commenters[login],
|
||||
"avatarUrl": user.avatarUrl,
|
||||
"url": user.url,
|
||||
}
|
||||
)
|
||||
|
||||
experts = get_users_to_write(
|
||||
counter=experts_results.commenters,
|
||||
authors=authors,
|
||||
)
|
||||
last_month_experts = get_users_to_write(
|
||||
counter=experts_results.last_month_commenters,
|
||||
authors=authors,
|
||||
)
|
||||
three_months_experts = get_users_to_write(
|
||||
counter=experts_results.three_months_commenters,
|
||||
authors=authors,
|
||||
)
|
||||
six_months_experts = get_users_to_write(
|
||||
counter=experts_results.six_months_commenters,
|
||||
authors=authors,
|
||||
)
|
||||
one_year_experts = get_users_to_write(
|
||||
counter=experts_results.one_year_commenters,
|
||||
authors=authors,
|
||||
)
|
||||
|
||||
people = {
|
||||
"maintainers": maintainers,
|
||||
"experts": experts,
|
||||
"last_month_experts": last_month_experts,
|
||||
"three_months_experts": three_months_experts,
|
||||
"six_months_experts": six_months_experts,
|
||||
"one_year_experts": one_year_experts,
|
||||
}
|
||||
|
||||
# For local development
|
||||
# people_path = Path("../docs/en/data/people.yml")
|
||||
people_path = Path("./docs/en/data/people.yml")
|
||||
|
||||
updated = update_content(content_path=people_path, new_content=people)
|
||||
|
||||
if not updated:
|
||||
logging.info("The data hasn't changed, finishing.")
|
||||
return
|
||||
|
||||
logging.info("Setting up GitHub Actions git user")
|
||||
subprocess.run(["git", "config", "user.name", "github-actions"], check=True)
|
||||
subprocess.run(
|
||||
["git", "config", "user.email", "github-actions@github.com"], check=True
|
||||
)
|
||||
branch_name = f"fastapi-people-experts-{secrets.token_hex(4)}"
|
||||
logging.info(f"Creating a new branch {branch_name}")
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
|
||||
logging.info("Adding updated file")
|
||||
subprocess.run(["git", "add", str(people_path)], check=True)
|
||||
logging.info("Committing updated file")
|
||||
message = "👥 Update FastAPI People - Experts"
|
||||
subprocess.run(["git", "commit", "-m", message], check=True)
|
||||
logging.info("Pushing branch")
|
||||
subprocess.run(["git", "push", "origin", branch_name], check=True)
|
||||
logging.info("Creating PR")
|
||||
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
|
||||
logging.info(f"Created PR: {pr.number}")
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("link", name="/items/").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"]
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,38 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("button", name="GET /items/ Read Items").click()
|
||||
page.get_by_role("button", name="Try it out").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/header_param_models/tutorial001.py"]
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,41 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("button", name="GET /items/ Read Items").click()
|
||||
page.get_by_role("button", name="Try it out").click()
|
||||
page.get_by_role("heading", name="Servers").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/query_param_models/tutorial001.py"]
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,38 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("button", name="POST /login/ Login").click()
|
||||
page.get_by_role("button", name="Try it out").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/request_form_models/tutorial001.py"]
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,32 @@
|
||||
import subprocess
|
||||
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_text("POST/items/Create Item").click()
|
||||
page.get_by_role("tab", name="Schema").first.click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(
|
||||
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png"
|
||||
)
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
|
||||
)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,33 @@
|
||||
import subprocess
|
||||
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_text("GET/items/Read Items").click()
|
||||
page.get_by_role("button", name="Try it out").click()
|
||||
page.get_by_role("button", name="Execute").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(
|
||||
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png"
|
||||
)
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
|
||||
)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,33 @@
|
||||
import subprocess
|
||||
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_text("GET/items/Read Items").click()
|
||||
page.get_by_role("tab", name="Schema").click()
|
||||
page.get_by_label("Schema").get_by_role("button", name="Expand all").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(
|
||||
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png"
|
||||
)
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
|
||||
)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,32 @@
|
||||
import subprocess
|
||||
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("button", name="Item-Input").click()
|
||||
page.get_by_role("button", name="Item-Output").click()
|
||||
page.set_viewport_size({"width": 960, "height": 820})
|
||||
# Manually add the screenshot
|
||||
page.screenshot(
|
||||
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png"
|
||||
)
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"]
|
||||
)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,32 @@
|
||||
import subprocess
|
||||
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_role("button", name="Item", exact=True).click()
|
||||
page.set_viewport_size({"width": 960, "height": 700})
|
||||
# Manually add the screenshot
|
||||
page.screenshot(
|
||||
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png"
|
||||
)
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["uvicorn", "docs_src.separate_openapi_schemas.tutorial002:app"]
|
||||
)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,37 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_label("post /heroes/").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/sql_databases/tutorial001.py"],
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,37 @@
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from playwright.sync_api import Playwright, sync_playwright
|
||||
|
||||
|
||||
# Run playwright codegen to generate the code below, copy paste the sections in run()
|
||||
def run(playwright: Playwright) -> None:
|
||||
browser = playwright.chromium.launch(headless=False)
|
||||
# Update the viewport manually
|
||||
context = browser.new_context(viewport={"width": 960, "height": 1080})
|
||||
page = context.new_page()
|
||||
page.goto("http://localhost:8000/docs")
|
||||
page.get_by_label("post /heroes/").click()
|
||||
# Manually add the screenshot
|
||||
page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png")
|
||||
|
||||
# ---------------------
|
||||
context.close()
|
||||
browser.close()
|
||||
|
||||
|
||||
process = subprocess.Popen(
|
||||
["fastapi", "run", "docs_src/sql_databases/tutorial002.py"],
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
try:
|
||||
response = httpx.get("http://localhost:8000/docs")
|
||||
except httpx.ConnectError:
|
||||
time.sleep(1)
|
||||
break
|
||||
with sync_playwright() as playwright:
|
||||
run(playwright)
|
||||
finally:
|
||||
process.terminate()
|
||||
@@ -0,0 +1,221 @@
|
||||
import logging
|
||||
import secrets
|
||||
import subprocess
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from github import Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
github_graphql_url = "https://api.github.com/graphql"
|
||||
|
||||
|
||||
sponsors_query = """
|
||||
query Q($after: String) {
|
||||
user(login: "tiangolo") {
|
||||
sponsorshipsAsMaintainer(first: 100, after: $after) {
|
||||
edges {
|
||||
cursor
|
||||
node {
|
||||
sponsorEntity {
|
||||
... on Organization {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
... on User {
|
||||
login
|
||||
avatarUrl
|
||||
url
|
||||
}
|
||||
}
|
||||
tier {
|
||||
name
|
||||
monthlyPriceInDollars
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class SponsorEntity(BaseModel):
|
||||
login: str
|
||||
avatarUrl: str
|
||||
url: str
|
||||
|
||||
|
||||
class Tier(BaseModel):
|
||||
name: str
|
||||
monthlyPriceInDollars: float
|
||||
|
||||
|
||||
class SponsorshipAsMaintainerNode(BaseModel):
|
||||
sponsorEntity: SponsorEntity
|
||||
tier: Tier
|
||||
|
||||
|
||||
class SponsorshipAsMaintainerEdge(BaseModel):
|
||||
cursor: str
|
||||
node: SponsorshipAsMaintainerNode
|
||||
|
||||
|
||||
class SponsorshipAsMaintainer(BaseModel):
|
||||
edges: list[SponsorshipAsMaintainerEdge]
|
||||
|
||||
|
||||
class SponsorsUser(BaseModel):
|
||||
sponsorshipsAsMaintainer: SponsorshipAsMaintainer
|
||||
|
||||
|
||||
class SponsorsResponseData(BaseModel):
|
||||
user: SponsorsUser
|
||||
|
||||
|
||||
class SponsorsResponse(BaseModel):
|
||||
data: SponsorsResponseData
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
sponsors_token: SecretStr
|
||||
pr_token: SecretStr
|
||||
github_repository: str
|
||||
httpx_timeout: int = 30
|
||||
|
||||
|
||||
def get_graphql_response(
|
||||
*,
|
||||
settings: Settings,
|
||||
query: str,
|
||||
after: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
headers = {"Authorization": f"token {settings.sponsors_token.get_secret_value()}"}
|
||||
variables = {"after": after}
|
||||
response = httpx.post(
|
||||
github_graphql_url,
|
||||
headers=headers,
|
||||
timeout=settings.httpx_timeout,
|
||||
json={"query": query, "variables": variables, "operationName": "Q"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
logging.error(f"Response was not 200, after: {after}")
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
data = response.json()
|
||||
if "errors" in data:
|
||||
logging.error(f"Errors in response, after: {after}")
|
||||
logging.error(data["errors"])
|
||||
logging.error(response.text)
|
||||
raise RuntimeError(response.text)
|
||||
return data
|
||||
|
||||
|
||||
def get_graphql_sponsor_edges(
|
||||
*, settings: Settings, after: str | None = None
|
||||
) -> list[SponsorshipAsMaintainerEdge]:
|
||||
data = get_graphql_response(settings=settings, query=sponsors_query, after=after)
|
||||
graphql_response = SponsorsResponse.model_validate(data)
|
||||
return graphql_response.data.user.sponsorshipsAsMaintainer.edges
|
||||
|
||||
|
||||
def get_individual_sponsors(
|
||||
settings: Settings,
|
||||
) -> defaultdict[float, dict[str, SponsorEntity]]:
|
||||
nodes: list[SponsorshipAsMaintainerNode] = []
|
||||
edges = get_graphql_sponsor_edges(settings=settings)
|
||||
|
||||
while edges:
|
||||
for edge in edges:
|
||||
nodes.append(edge.node)
|
||||
last_edge = edges[-1]
|
||||
edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor)
|
||||
|
||||
tiers: defaultdict[float, dict[str, SponsorEntity]] = defaultdict(dict)
|
||||
for node in nodes:
|
||||
tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = (
|
||||
node.sponsorEntity
|
||||
)
|
||||
return tiers
|
||||
|
||||
|
||||
def update_content(*, content_path: Path, new_content: Any) -> bool:
|
||||
old_content = content_path.read_text(encoding="utf-8")
|
||||
|
||||
new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True)
|
||||
if old_content == new_content:
|
||||
logging.info(f"The content hasn't changed for {content_path}")
|
||||
return False
|
||||
content_path.write_text(new_content, encoding="utf-8")
|
||||
logging.info(f"Updated {content_path}")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
logging.info(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.pr_token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
|
||||
tiers = get_individual_sponsors(settings=settings)
|
||||
keys = list(tiers.keys())
|
||||
keys.sort(reverse=True)
|
||||
sponsors = []
|
||||
for key in keys:
|
||||
sponsor_group = []
|
||||
for login, sponsor in tiers[key].items():
|
||||
sponsor_group.append(
|
||||
{"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url}
|
||||
)
|
||||
sponsors.append(sponsor_group)
|
||||
github_sponsors = {
|
||||
"sponsors": sponsors,
|
||||
}
|
||||
|
||||
# For local development
|
||||
# github_sponsors_path = Path("../docs/en/data/github_sponsors.yml")
|
||||
github_sponsors_path = Path("./docs/en/data/github_sponsors.yml")
|
||||
updated = update_content(
|
||||
content_path=github_sponsors_path, new_content=github_sponsors
|
||||
)
|
||||
|
||||
if not updated:
|
||||
logging.info("The data hasn't changed, finishing.")
|
||||
return
|
||||
|
||||
logging.info("Setting up GitHub Actions git user")
|
||||
subprocess.run(["git", "config", "user.name", "github-actions"], check=True)
|
||||
subprocess.run(
|
||||
["git", "config", "user.email", "github-actions@github.com"], check=True
|
||||
)
|
||||
branch_name = f"fastapi-people-sponsors-{secrets.token_hex(4)}"
|
||||
logging.info(f"Creating a new branch {branch_name}")
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
|
||||
logging.info("Adding updated file")
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"add",
|
||||
str(github_sponsors_path),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
logging.info("Committing updated file")
|
||||
message = "👥 Update FastAPI People - Sponsors"
|
||||
subprocess.run(["git", "commit", "-m", message], check=True)
|
||||
logging.info("Pushing branch")
|
||||
subprocess.run(["git", "push", "origin", branch_name], check=True)
|
||||
logging.info("Creating PR")
|
||||
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
|
||||
logging.info(f"Created PR: {pr.number}")
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
bash scripts/test.sh ${@}
|
||||
bash scripts/coverage.sh
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
export PYTHONPATH=./docs_src
|
||||
coverage run -m pytest tests ${@}
|
||||
@@ -0,0 +1,80 @@
|
||||
import logging
|
||||
import secrets
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from github import Github
|
||||
from pydantic import BaseModel, SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_repository: str
|
||||
github_token: SecretStr
|
||||
|
||||
|
||||
class Repo(BaseModel):
|
||||
name: str
|
||||
html_url: str
|
||||
stars: int
|
||||
owner_login: str
|
||||
owner_html_url: str
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
|
||||
logging.info(f"Using config: {settings.model_dump_json()}")
|
||||
g = Github(settings.github_token.get_secret_value(), per_page=100)
|
||||
r = g.get_repo(settings.github_repository)
|
||||
repos = g.search_repositories(query="topic:fastapi")
|
||||
repos_list = list(repos)
|
||||
final_repos: list[Repo] = []
|
||||
for repo in repos_list[:100]:
|
||||
if repo.full_name == settings.github_repository:
|
||||
continue
|
||||
final_repos.append(
|
||||
Repo(
|
||||
name=repo.name,
|
||||
html_url=repo.html_url,
|
||||
stars=repo.stargazers_count,
|
||||
owner_login=repo.owner.login,
|
||||
owner_html_url=repo.owner.html_url,
|
||||
)
|
||||
)
|
||||
data = [repo.model_dump() for repo in final_repos]
|
||||
|
||||
# Local development
|
||||
# repos_path = Path("../docs/en/data/topic_repos.yml")
|
||||
repos_path = Path("./docs/en/data/topic_repos.yml")
|
||||
repos_old_content = repos_path.read_text(encoding="utf-8")
|
||||
new_repos_content = yaml.dump(data, sort_keys=False, width=200, allow_unicode=True)
|
||||
if repos_old_content == new_repos_content:
|
||||
logging.info("The data hasn't changed. Finishing.")
|
||||
return
|
||||
repos_path.write_text(new_repos_content, encoding="utf-8")
|
||||
logging.info("Setting up GitHub Actions git user")
|
||||
subprocess.run(["git", "config", "user.name", "github-actions"], check=True)
|
||||
subprocess.run(
|
||||
["git", "config", "user.email", "github-actions@github.com"], check=True
|
||||
)
|
||||
branch_name = f"fastapi-topic-repos-{secrets.token_hex(4)}"
|
||||
logging.info(f"Creating a new branch {branch_name}")
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
|
||||
logging.info("Adding updated file")
|
||||
subprocess.run(["git", "add", str(repos_path)], check=True)
|
||||
logging.info("Committing updated file")
|
||||
message = "👥 Update FastAPI GitHub topic repositories"
|
||||
subprocess.run(["git", "commit", "-m", message], check=True)
|
||||
logging.info("Pushing branch")
|
||||
subprocess.run(["git", "push", "origin", branch_name], check=True)
|
||||
logging.info("Creating PR")
|
||||
pr = r.create_pull(title=message, body=message, base="master", head=branch_name)
|
||||
logging.info(f"Created PR: {pr.number}")
|
||||
logging.info("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,981 @@
|
||||
import secrets
|
||||
import subprocess
|
||||
from collections.abc import Iterable
|
||||
from functools import lru_cache
|
||||
from os import sep as pathsep
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
import git
|
||||
import typer
|
||||
import yaml
|
||||
from github import Github
|
||||
from pydantic_ai import Agent
|
||||
from rich import print
|
||||
|
||||
non_translated_sections = (
|
||||
f"reference{pathsep}",
|
||||
"release-notes.md",
|
||||
"fastapi-people.md",
|
||||
"external-links.md",
|
||||
"newsletter.md",
|
||||
"management-tasks.md",
|
||||
"management.md",
|
||||
"contributing.md",
|
||||
)
|
||||
|
||||
|
||||
general_prompt = """
|
||||
### About literal text in this prompt
|
||||
|
||||
1) In the following instructions (after I say: `The above rules are in effect now`) the two characters `«` and `»` will be used to surround LITERAL TEXT, which is text or characters you shall interpret literally. The `«` and the `»` are not part of the literal text, they are the meta characters denoting it.
|
||||
|
||||
2) Furthermore, text surrounded by `«««` and `»»»` is a BLOCK OF LITERAL TEXT which spans multiple lines. To get its content, dedent all lines of the block until the `«««` and `»»»` are at column zero, then remove the newline (`\n`) after the `«««` and the newline before the `»»»`. The `«««` and the `»»»` are not part of the literal text block, they are the meta characters denoting it.
|
||||
|
||||
3) If you see backticks or any other quotes inside literal text – inside `«` and `»` – or inside blocks of literal text – inside `«««` and `»»»` – then interpret them as literal characters, do NOT interpret them as meta characters.
|
||||
|
||||
The above rules are in effect now.
|
||||
|
||||
|
||||
### Definitions of terms used in this prompt
|
||||
|
||||
"backtick"
|
||||
|
||||
The character «`»
|
||||
Unicode U+0060 (GRAVE ACCENT)
|
||||
|
||||
"single backtick"
|
||||
|
||||
A single backtick – «`»
|
||||
|
||||
"triple backticks"
|
||||
|
||||
Three backticks in a row – «```»
|
||||
|
||||
"neutral double quote"
|
||||
|
||||
The character «"»
|
||||
Unicode U+0022 (QUOTATION MARK)
|
||||
|
||||
"neutral single quote"
|
||||
|
||||
The character «'»
|
||||
Unicode U+0027 (APOSTROPHE)
|
||||
|
||||
"English double typographic quotes"
|
||||
|
||||
The characters «“» and «”»
|
||||
Unicode U+201C (LEFT DOUBLE QUOTATION MARK) and Unicode U+201D (RIGHT DOUBLE QUOTATION MARK)
|
||||
|
||||
"English single typographic quotes"
|
||||
|
||||
The characters «‘» and «’»
|
||||
Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and Unicode U+2019 (RIGHT SINGLE QUOTATION MARK)
|
||||
|
||||
"code snippet"
|
||||
|
||||
Also called "inline code". Text in a Markdown document which is surrounded by single backticks. A paragraph in a Markdown document can have a more than one code snippet.
|
||||
|
||||
Example:
|
||||
|
||||
«««
|
||||
`i am a code snippet`
|
||||
»»»
|
||||
|
||||
Example:
|
||||
|
||||
«««
|
||||
`first code snippet` `second code snippet` `third code snippet`
|
||||
»»»
|
||||
|
||||
"code block"
|
||||
|
||||
Text in a Markdown document which is surrounded by triple backticks. Spreads multiple lines.
|
||||
|
||||
Example:
|
||||
|
||||
«««
|
||||
```
|
||||
Hello
|
||||
World
|
||||
```
|
||||
»»»
|
||||
|
||||
Example:
|
||||
|
||||
«««
|
||||
```python
|
||||
print("hello World")
|
||||
```
|
||||
»»»
|
||||
|
||||
"HTML element"
|
||||
|
||||
a HTML opening tag – e.g. «<div>» – and a HTML closing tag – e.g. «</div>» – surrounding text or other HTML elements.
|
||||
|
||||
|
||||
### Your task
|
||||
|
||||
Translate an English text – the original content – to a target language.
|
||||
|
||||
The original content is written in Markdown, write the translation in Markdown as well.
|
||||
|
||||
The original content will be surrounded by triple percentage signs («%%%»). Do not include the triple percentage signs in the translation.
|
||||
|
||||
|
||||
### Technical terms in English
|
||||
|
||||
For technical terms in English that don't have a common translation term, use the original term in English.
|
||||
|
||||
|
||||
### Content of code snippets
|
||||
|
||||
Do not translate the content of code snippets, keep the original in English. For example, «`list`», «`dict`», keep them as is.
|
||||
|
||||
|
||||
### Content of code blocks
|
||||
|
||||
Do not translate the content of code blocks, except for comments in the language which the code block uses.
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English) – The code block is a bash code example with one comment:
|
||||
|
||||
«««
|
||||
```bash
|
||||
# Print greeting
|
||||
echo "Hello, World!"
|
||||
```
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
```bash
|
||||
# Gruß ausgeben
|
||||
echo "Hello, World!"
|
||||
```
|
||||
»»»
|
||||
|
||||
Source (English) – The code block is a console example containing HTML tags. No comments, so nothing to change here:
|
||||
|
||||
«««
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> run <u style="text-decoration-style:solid">main.py</u>
|
||||
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting server
|
||||
Searching for package file structure
|
||||
```
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> run <u style="text-decoration-style:solid">main.py</u>
|
||||
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting server
|
||||
Searching for package file structure
|
||||
```
|
||||
»»»
|
||||
|
||||
Source (English) – The code block is a console example containing 5 comments:
|
||||
|
||||
«««
|
||||
```console
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// Create a directory for this project
|
||||
$ mkdir awesome-project
|
||||
// Enter into that project directory
|
||||
$ cd awesome-project
|
||||
```
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
```console
|
||||
// Gehe zum Home-Verzeichnis
|
||||
$ cd
|
||||
// Erstelle ein Verzeichnis für alle Ihre Code-Projekte
|
||||
$ mkdir code
|
||||
// Gehe in dieses Code-Verzeichnis
|
||||
$ cd code
|
||||
// Erstelle ein Verzeichnis für dieses Projekt
|
||||
$ mkdir awesome-project
|
||||
// Gehe in dieses Projektverzeichnis
|
||||
$ cd awesome-project
|
||||
```
|
||||
»»»
|
||||
|
||||
If there is an existing translation and its Mermaid diagram is in sync with the Mermaid diagram in the English source, except a few translated words, then use the Mermaid diagram of the existing translation. The human editor of the translation translated these words in the Mermaid diagram. Keep these translations, do not revert them back to the English source.
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[global env]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) -->|requires| harry-1
|
||||
end
|
||||
```
|
||||
»»»
|
||||
|
||||
Existing translation (German) – has three translations:
|
||||
|
||||
«««
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[globale Umgebung]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone-Projekt]
|
||||
stone(philosophers-stone) -->|benötigt| harry-1
|
||||
end
|
||||
```
|
||||
»»»
|
||||
|
||||
Result (German) – you change nothing:
|
||||
|
||||
«««
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[globale Umgebung]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone-Projekt]
|
||||
stone(philosophers-stone) -->|benötigt| harry-1
|
||||
end
|
||||
```
|
||||
»»»
|
||||
|
||||
|
||||
### Special blocks
|
||||
|
||||
There are special blocks of notes, tips and others that look like:
|
||||
|
||||
«««
|
||||
/// note
|
||||
»»»
|
||||
|
||||
To translate it, keep the same line and add the translation after a vertical bar.
|
||||
|
||||
For example, if you were translating to Spanish, you would write:
|
||||
|
||||
«««
|
||||
/// note | Nota
|
||||
»»»
|
||||
|
||||
Some examples in Spanish:
|
||||
|
||||
Source:
|
||||
|
||||
«««
|
||||
/// tip
|
||||
»»»
|
||||
|
||||
Result:
|
||||
|
||||
«««
|
||||
/// tip | Consejo
|
||||
»»»
|
||||
|
||||
Source:
|
||||
|
||||
«««
|
||||
/// details | Preview
|
||||
»»»
|
||||
|
||||
Result:
|
||||
|
||||
«««
|
||||
/// details | Vista previa
|
||||
»»»
|
||||
|
||||
|
||||
### Tab blocks
|
||||
|
||||
There are special blocks surrounded by four slashes («////»). They mark text, which will be rendered as part of a tab in the final document. The scheme is:
|
||||
|
||||
//// tab | {tab title}
|
||||
{tab content, may span many lines}
|
||||
////
|
||||
|
||||
Keep everything before the vertical bar («|») as is, including the vertical bar. Translate the tab title. Translate the tab content, applying the rules you know. Keep the four block closing slashes as is.
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
//// tab | Python 3.8+ non-Annotated
|
||||
Hello
|
||||
////
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
//// tab | Python 3.8+ nicht annotiert
|
||||
Hallo
|
||||
////
|
||||
»»»
|
||||
|
||||
Source (English) – Here there is nothing to translate in the tab title:
|
||||
|
||||
«««
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
Hello again
|
||||
////
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
Hallo wieder
|
||||
////
|
||||
»»»
|
||||
|
||||
|
||||
### Headings
|
||||
|
||||
Every Markdown heading in the English text (all levels) ends with a part inside curly brackets. This part denotes the hash of this heading, which is used in links to this heading. In translations, translate the heading, but do not translate this hash part, so that links do not break.
|
||||
|
||||
Examples of how to translate a heading:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
## Alternative API docs { #alternative-api-docs }
|
||||
»»»
|
||||
|
||||
Result (Spanish):
|
||||
|
||||
«««
|
||||
## Documentación de la API alternativa { #alternative-api-docs }
|
||||
»»»
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
### Example { #example }
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
### Beispiel { #example }
|
||||
»»»
|
||||
|
||||
|
||||
### Links
|
||||
|
||||
Use the following rules for links (apply both to Markdown-style links ([text](url)) and to HTML-style <a> tags):
|
||||
|
||||
1) For relative URLs, only translate link text. Do not translate the URL or its parts
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
[One of the fastest Python frameworks available](#performance)
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
[Eines der schnellsten verfügbaren Python-Frameworks](#performance)
|
||||
»»»
|
||||
|
||||
2) For absolute URLs which DO NOT start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and leave the URL unchanged.
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel docs</a>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel-Dokumentation</a>
|
||||
»»»
|
||||
|
||||
3) For absolute URLs which DO start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and change the URL by adding language code («https://fastapi.tiangolo.com/{language_code}[rest part of the url]»).
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<a href="https://fastapi.tiangolo.com/tutorial/path-params/#documentation" class="external-link" target="_blank">Documentation</a>
|
||||
»»»
|
||||
|
||||
Result (Spanish):
|
||||
|
||||
«««
|
||||
<a href="https://fastapi.tiangolo.com/es/tutorial/path-params/#documentation" class="external-link" target="_blank">Documentación</a>
|
||||
»»»
|
||||
|
||||
3.1) Do not add language codes for URLs that point to static assets (e.g., images, CSS, JavaScript).
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<a href="https://fastapi.tiangolo.com/img/something.jpg" class="external-link" target="_blank">Something</a>
|
||||
»»»
|
||||
|
||||
Result (Spanish):
|
||||
|
||||
«««
|
||||
<a href="https://fastapi.tiangolo.com/img/something.jpg" class="external-link" target="_blank">Algo</a>
|
||||
»»»
|
||||
|
||||
4) For internal links, only translate link text.
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
[Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
[Pull Requests erzeugen](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
5) Do not translate anchor fragments in links (the part after «#»), as they must remain the same to work correctly.
|
||||
|
||||
5.1) If an existing translation has a link with an anchor fragment different to the anchor fragment in the English source, then this is an error. Fix this by using the anchor fragment of the English source.
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
Existing wrong translation (German) – notice the wrongly translated anchor fragment:
|
||||
|
||||
«««
|
||||
[Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=_blank}.
|
||||
»»»
|
||||
|
||||
Result (German) – you fix the anchor fragment:
|
||||
|
||||
«««
|
||||
[Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
|
||||
»»»
|
||||
|
||||
5.2) Do not add anchor fragments at will, even if this makes sense. If the English source has no anchor, don't add one.
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
Create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
Wrong translation (German) – Anchor added to the URL.
|
||||
|
||||
«««
|
||||
Erstelle eine [virtuelle Umgebung](../virtual-environments.md#create-a-virtual-environment){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
Good translation (German) – URL stays like in the English source.
|
||||
|
||||
«««
|
||||
Erstelle eine [Virtuelle Umgebung](../virtual-environments.md){.internal-link target=_blank}
|
||||
»»»
|
||||
|
||||
|
||||
### HTML abbr elements
|
||||
|
||||
Translate HTML abbr elements («<abbr title="description">text</abbr>») as follows:
|
||||
|
||||
1) If the text surrounded by the abbr element is an abbreviation (the text may be surrounded by further HTML or Markdown markup or quotes, for example «<code>text</code>» or «`text`» or «"text"», ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash («–») to the full phrase, followed by the translation of the full phrase.
|
||||
|
||||
Conversion scheme:
|
||||
|
||||
Source (English):
|
||||
|
||||
<abbr title="{full phrase}">{abbreviation}</abbr>
|
||||
|
||||
Result:
|
||||
|
||||
<abbr title="{full phrase} – {translation of full phrase}">{abbreviation}</abbr>
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<abbr title="Internet of Things">IoT</abbr>
|
||||
<abbr title="Central Processing Unit">CPU</abbr>
|
||||
<abbr title="too long; didn't read"><strong>TL;DR:</strong></abbr>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<abbr title="Internet of Things – Internet der Dinge">IoT</abbr>
|
||||
<abbr title="Central Processing Unit – Zentrale Verarbeitungseinheit">CPU</abbr>
|
||||
<abbr title="too long; didn't read – zu lang; hab's nicht gelesen"><strong>TL;DR:</strong></abbr>
|
||||
»»»
|
||||
|
||||
1.1) If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.
|
||||
|
||||
Conversion scheme:
|
||||
|
||||
Source (English):
|
||||
|
||||
<abbr title="{full phrase}">{abbreviation}</abbr>
|
||||
|
||||
Result:
|
||||
|
||||
<abbr title="{translation of full phrase}">{abbreviation}</abbr>
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<abbr title="JSON Web Tokens">JWT</abbr>
|
||||
<abbr title="Enumeration">Enum</abbr>
|
||||
<abbr title="Asynchronous Server Gateway Interface">ASGI</abbr>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<abbr title="JSON Web Tokens">JWT</abbr>
|
||||
<abbr title="Enumeration">Enum</abbr>
|
||||
<abbr title="Asynchrones Server-Gateway-Interface">ASGI</abbr>
|
||||
»»»
|
||||
|
||||
2) If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.
|
||||
|
||||
Conversion scheme:
|
||||
|
||||
Source (English):
|
||||
|
||||
<abbr title="{description}">{text}</abbr>
|
||||
|
||||
Result:
|
||||
|
||||
<abbr title="{translation of description}">{translation of text}</abbr>
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<abbr title="also known as: endpoints, routes">path</abbr>
|
||||
<abbr title="a program that checks for code errors">linter</abbr>
|
||||
<abbr title="converting the string that comes from an HTTP request into Python data">parsing</abbr>
|
||||
<abbr title="before 2023-03">0.95.0</abbr>
|
||||
<abbr title="2023-08-26">at the time of writing this</abbr>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<abbr title="auch bekannt als: Endpunkte, Routen">Pfad</abbr>
|
||||
<abbr title="Programm das auf Fehler im Code prüft">Linter</abbr>
|
||||
<abbr title="Konvertieren des Strings eines HTTP-Requests in Python-Daten">Parsen</abbr>
|
||||
<abbr title="vor 2023-03">0.95.0</abbr>
|
||||
<abbr title="2023-08-26">zum Zeitpunkt als das hier geschrieben wurde</abbr>
|
||||
»»»
|
||||
|
||||
|
||||
3) If the text surrounded by the abbr element is an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon («:»), then append a dash («–») and the translation of the full phrase to the original full phrase and translate the other information.
|
||||
|
||||
Conversion scheme:
|
||||
|
||||
Source (English):
|
||||
|
||||
<abbr title="{full phrase}: {other information}">{abbreviation}</abbr>
|
||||
|
||||
Result:
|
||||
|
||||
<abbr title="{full phrase} – {translation of full phrase}: {translation of other information}">{abbreviation}</abbr>
|
||||
|
||||
Examples:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<abbr title="Input/Output: disk reading or writing, network communication.">I/O</abbr>
|
||||
<abbr title="Content Delivery Network: service, that provides static files.">CDN</abbr>
|
||||
<abbr title="Integrated Development Environment: similar to a code editor">IDE</abbr>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<abbr title="Input/Output – Eingabe/Ausgabe: Lesen oder Schreiben auf der Festplatte, Netzwerkkommunikation.">I/O</abbr>
|
||||
<abbr title="Content Delivery Network – Inhalte auslieferndes Netzwerk: Dienst, der statische Dateien bereitstellt.">CDN</abbr>
|
||||
<abbr title="Integrated Development Environment – Integrierte Entwicklungsumgebung: Ähnlich einem Code-Editor">IDE</abbr>
|
||||
»»»
|
||||
|
||||
3.1) Like in rule 2.1, you can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.
|
||||
|
||||
Conversion scheme:
|
||||
|
||||
Source (English):
|
||||
|
||||
<abbr title="{full phrase}: {information}">{abbreviation}</abbr>
|
||||
|
||||
Result:
|
||||
|
||||
<abbr title="{translation of full phrase}: {translation of information}">{abbreviation}</abbr>
|
||||
|
||||
Example:
|
||||
|
||||
Source (English):
|
||||
|
||||
«««
|
||||
<abbr title="Object Relational Mapper: a fancy term for a library where some classes represent SQL tables and instances represent rows in those tables">ORM</abbr>
|
||||
»»»
|
||||
|
||||
Result (German):
|
||||
|
||||
«««
|
||||
<abbr title="Objektrelationaler Mapper: Ein Fachbegriff für eine Bibliothek, in der einige Klassen SQL-Tabellen und Instanzen Zeilen in diesen Tabellen darstellen">ORM</abbr>
|
||||
»»»
|
||||
|
||||
4) If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by the human editor of the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.
|
||||
|
||||
5) Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's from rule 4 alone. Do not change their formatting or content.
|
||||
|
||||
"""
|
||||
|
||||
app = typer.Typer()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_langs() -> dict[str, str]:
|
||||
return yaml.safe_load(Path("docs/language_names.yml").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def generate_lang_path(*, lang: str, path: Path) -> Path:
|
||||
en_docs_path = Path("docs/en/docs")
|
||||
assert str(path).startswith(str(en_docs_path)), (
|
||||
f"Path must be inside {en_docs_path}"
|
||||
)
|
||||
lang_docs_path = Path(f"docs/{lang}/docs")
|
||||
out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path)))
|
||||
return out_path
|
||||
|
||||
|
||||
def generate_en_path(*, lang: str, path: Path) -> Path:
|
||||
en_docs_path = Path("docs/en/docs")
|
||||
assert not str(path).startswith(str(en_docs_path)), (
|
||||
f"Path must not be inside {en_docs_path}"
|
||||
)
|
||||
lang_docs_path = Path(f"docs/{lang}/docs")
|
||||
out_path = Path(str(path).replace(str(lang_docs_path), str(en_docs_path)))
|
||||
return out_path
|
||||
|
||||
|
||||
@app.command()
|
||||
def translate_page(
|
||||
*,
|
||||
language: Annotated[str, typer.Option(envvar="LANGUAGE")],
|
||||
en_path: Annotated[Path, typer.Option(envvar="EN_PATH")],
|
||||
) -> None:
|
||||
assert language != "en", (
|
||||
"`en` is the source language, choose another language as translation target"
|
||||
)
|
||||
langs = get_langs()
|
||||
language_name = langs[language]
|
||||
lang_path = Path(f"docs/{language}")
|
||||
lang_path.mkdir(exist_ok=True)
|
||||
lang_prompt_path = lang_path / "llm-prompt.md"
|
||||
assert lang_prompt_path.exists(), f"Prompt file not found: {lang_prompt_path}"
|
||||
lang_prompt_content = lang_prompt_path.read_text(encoding="utf-8")
|
||||
|
||||
en_docs_path = Path("docs/en/docs")
|
||||
assert str(en_path).startswith(str(en_docs_path)), (
|
||||
f"Path must be inside {en_docs_path}"
|
||||
)
|
||||
out_path = generate_lang_path(lang=language, path=en_path)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
original_content = en_path.read_text(encoding="utf-8")
|
||||
old_translation: str | None = None
|
||||
if out_path.exists():
|
||||
print(f"Found existing translation: {out_path}")
|
||||
old_translation = out_path.read_text(encoding="utf-8")
|
||||
print(f"Translating {en_path} to {language} ({language_name})")
|
||||
agent = Agent("openai:gpt-5")
|
||||
|
||||
prompt_segments = [
|
||||
general_prompt,
|
||||
lang_prompt_content,
|
||||
]
|
||||
if old_translation:
|
||||
prompt_segments.extend(
|
||||
[
|
||||
"There is an existing previous translation for the original English content, that may be outdated.",
|
||||
"Update the translation only where necessary:",
|
||||
"- If the original English content has added parts, also add these parts to the translation.",
|
||||
"- If the original English content has removed parts, also remove them from the translation, unless you were instructed earlier to not do that in specific cases.",
|
||||
"- If parts of the original English content have changed, also change those parts in the translation.",
|
||||
"- If the previous translation violates current instructions, update it.",
|
||||
"- Otherwise, preserve the original translation LINE-BY-LINE, AS-IS.",
|
||||
"Do not:",
|
||||
"- rephrase or rewrite correct lines just to improve the style.",
|
||||
"- add or remove line breaks, unless the original English content changed.",
|
||||
"- change formatting or whitespace unless absolutely required.",
|
||||
"Only change what must be changed. The goal is to minimize diffs for easier human review.",
|
||||
"UNLESS you were instructed earlier to behave different, there MUST NOT be whole sentences or partial sentences in the updated translation, which are not in the original English content, and there MUST NOT be whole sentences or partial sentences in the original English content, which are not in the updated translation. Remember: the updated translation shall be IN SYNC with the original English content.",
|
||||
"Previous translation:",
|
||||
f"%%%\n{old_translation}%%%",
|
||||
]
|
||||
)
|
||||
prompt_segments.extend(
|
||||
[
|
||||
f"Translate to {language} ({language_name}).",
|
||||
"Original content:",
|
||||
f"%%%\n{original_content}%%%",
|
||||
]
|
||||
)
|
||||
prompt = "\n\n".join(prompt_segments)
|
||||
print(f"Running agent for {out_path}")
|
||||
result = agent.run_sync(prompt)
|
||||
out_content = f"{result.output.strip()}\n"
|
||||
print(f"Saving translation to {out_path}")
|
||||
out_path.write_text(out_content, encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def iter_all_en_paths() -> Iterable[Path]:
|
||||
"""
|
||||
Iterate on the markdown files to translate in order of priority.
|
||||
"""
|
||||
first_dirs = [
|
||||
Path("docs/en/docs/learn"),
|
||||
Path("docs/en/docs/tutorial"),
|
||||
Path("docs/en/docs/advanced"),
|
||||
Path("docs/en/docs/about"),
|
||||
Path("docs/en/docs/how-to"),
|
||||
]
|
||||
first_parent = Path("docs/en/docs")
|
||||
yield from first_parent.glob("*.md")
|
||||
for dir_path in first_dirs:
|
||||
yield from dir_path.rglob("*.md")
|
||||
first_dirs_str = tuple(str(d) for d in first_dirs)
|
||||
for path in Path("docs/en/docs").rglob("*.md"):
|
||||
if str(path).startswith(first_dirs_str):
|
||||
continue
|
||||
if path.parent == first_parent:
|
||||
continue
|
||||
yield path
|
||||
|
||||
|
||||
def iter_en_paths_to_translate() -> Iterable[Path]:
|
||||
en_docs_root = Path("docs/en/docs/")
|
||||
for path in iter_all_en_paths():
|
||||
relpath = path.relative_to(en_docs_root)
|
||||
if not str(relpath).startswith(non_translated_sections):
|
||||
yield path
|
||||
|
||||
|
||||
@app.command()
|
||||
def translate_lang(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
|
||||
paths_to_process = list(iter_en_paths_to_translate())
|
||||
print("Original paths:")
|
||||
for p in paths_to_process:
|
||||
print(f" - {p}")
|
||||
print(f"Total original paths: {len(paths_to_process)}")
|
||||
missing_paths: list[Path] = []
|
||||
skipped_paths: list[Path] = []
|
||||
for p in paths_to_process:
|
||||
lang_path = generate_lang_path(lang=language, path=p)
|
||||
if lang_path.exists():
|
||||
skipped_paths.append(p)
|
||||
continue
|
||||
missing_paths.append(p)
|
||||
print("Paths to skip:")
|
||||
for p in skipped_paths:
|
||||
print(f" - {p}")
|
||||
print(f"Total paths to skip: {len(skipped_paths)}")
|
||||
print("Paths to process:")
|
||||
for p in missing_paths:
|
||||
print(f" - {p}")
|
||||
print(f"Total paths to process: {len(missing_paths)}")
|
||||
for p in missing_paths:
|
||||
print(f"Translating: {p}")
|
||||
translate_page(language="es", en_path=p)
|
||||
print(f"Done translating: {p}")
|
||||
|
||||
|
||||
@app.command()
|
||||
def list_removable(language: str) -> list[Path]:
|
||||
removable_paths: list[Path] = []
|
||||
lang_paths = Path(f"docs/{language}").rglob("*.md")
|
||||
for path in lang_paths:
|
||||
en_path = generate_en_path(lang=language, path=path)
|
||||
if not en_path.exists():
|
||||
removable_paths.append(path)
|
||||
print(removable_paths)
|
||||
return removable_paths
|
||||
|
||||
|
||||
@app.command()
|
||||
def list_all_removable() -> list[Path]:
|
||||
all_removable_paths: list[Path] = []
|
||||
langs = get_langs()
|
||||
for lang in langs:
|
||||
if lang == "en":
|
||||
continue
|
||||
removable_paths = list_removable(lang)
|
||||
all_removable_paths.extend(removable_paths)
|
||||
print(all_removable_paths)
|
||||
return all_removable_paths
|
||||
|
||||
|
||||
@app.command()
|
||||
def remove_removable(language: str) -> None:
|
||||
removable_paths = list_removable(language)
|
||||
for path in removable_paths:
|
||||
path.unlink()
|
||||
print(f"Removed: {path}")
|
||||
print("Done removing all removable paths")
|
||||
|
||||
|
||||
@app.command()
|
||||
def remove_all_removable() -> None:
|
||||
all_removable = list_all_removable()
|
||||
for removable_path in all_removable:
|
||||
removable_path.unlink()
|
||||
print(f"Removed: {removable_path}")
|
||||
print("Done removing all removable paths")
|
||||
|
||||
|
||||
@app.command()
|
||||
def list_missing(language: str) -> list[Path]:
|
||||
missing_paths: list[Path] = []
|
||||
en_lang_paths = list(iter_en_paths_to_translate())
|
||||
for path in en_lang_paths:
|
||||
lang_path = generate_lang_path(lang=language, path=path)
|
||||
if not lang_path.exists():
|
||||
missing_paths.append(path)
|
||||
print(missing_paths)
|
||||
return missing_paths
|
||||
|
||||
|
||||
@app.command()
|
||||
def list_outdated(language: str) -> list[Path]:
|
||||
dir_path = Path(__file__).absolute().parent.parent
|
||||
repo = git.Repo(dir_path)
|
||||
|
||||
outdated_paths: list[Path] = []
|
||||
en_lang_paths = list(iter_en_paths_to_translate())
|
||||
for path in en_lang_paths:
|
||||
lang_path = generate_lang_path(lang=language, path=path)
|
||||
if not lang_path.exists():
|
||||
continue
|
||||
en_commit_datetime = list(repo.iter_commits(paths=path, max_count=1))[
|
||||
0
|
||||
].committed_datetime
|
||||
lang_commit_datetime = list(repo.iter_commits(paths=lang_path, max_count=1))[
|
||||
0
|
||||
].committed_datetime
|
||||
if lang_commit_datetime < en_commit_datetime:
|
||||
outdated_paths.append(path)
|
||||
print(outdated_paths)
|
||||
return outdated_paths
|
||||
|
||||
|
||||
@app.command()
|
||||
def update_outdated(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
|
||||
outdated_paths = list_outdated(language)
|
||||
for path in outdated_paths:
|
||||
print(f"Updating lang: {language} path: {path}")
|
||||
translate_page(language=language, en_path=path)
|
||||
print(f"Done updating: {path}")
|
||||
print("Done updating all outdated paths")
|
||||
|
||||
|
||||
@app.command()
|
||||
def add_missing(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
|
||||
missing_paths = list_missing(language)
|
||||
for path in missing_paths:
|
||||
print(f"Adding lang: {language} path: {path}")
|
||||
translate_page(language=language, en_path=path)
|
||||
print(f"Done adding: {path}")
|
||||
print("Done adding all missing paths")
|
||||
|
||||
|
||||
@app.command()
|
||||
def update_and_add(language: Annotated[str, typer.Option(envvar="LANGUAGE")]) -> None:
|
||||
print(f"Updating outdated translations for {language}")
|
||||
update_outdated(language=language)
|
||||
print(f"Adding missing translations for {language}")
|
||||
add_missing(language=language)
|
||||
print(f"Done updating and adding for {language}")
|
||||
|
||||
|
||||
@app.command()
|
||||
def make_pr(
|
||||
*,
|
||||
language: Annotated[str | None, typer.Option(envvar="LANGUAGE")] = None,
|
||||
github_token: Annotated[str, typer.Option(envvar="GITHUB_TOKEN")],
|
||||
github_repository: Annotated[str, typer.Option(envvar="GITHUB_REPOSITORY")],
|
||||
) -> None:
|
||||
print("Setting up GitHub Actions git user")
|
||||
repo = git.Repo(Path(__file__).absolute().parent.parent)
|
||||
if not repo.is_dirty(untracked_files=True):
|
||||
print("Repository is clean, no changes to commit")
|
||||
return
|
||||
subprocess.run(["git", "config", "user.name", "github-actions"], check=True)
|
||||
subprocess.run(
|
||||
["git", "config", "user.email", "github-actions@github.com"], check=True
|
||||
)
|
||||
branch_name = "translate"
|
||||
if language:
|
||||
branch_name += f"-{language}"
|
||||
branch_name += f"-{secrets.token_hex(4)}"
|
||||
print(f"Creating a new branch {branch_name}")
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], check=True)
|
||||
print("Adding updated files")
|
||||
git_path = Path("docs")
|
||||
subprocess.run(["git", "add", str(git_path)], check=True)
|
||||
print("Committing updated file")
|
||||
message = "🌐 Update translations"
|
||||
if language:
|
||||
message += f" for {language}"
|
||||
subprocess.run(["git", "commit", "-m", message], check=True)
|
||||
print("Pushing branch")
|
||||
subprocess.run(["git", "push", "origin", branch_name], check=True)
|
||||
print("Creating PR")
|
||||
g = Github(github_token)
|
||||
gh_repo = g.get_repo(github_repository)
|
||||
pr = gh_repo.create_pull(
|
||||
title=message, body=message, base="master", head=branch_name
|
||||
)
|
||||
print(f"Created PR: {pr.number}")
|
||||
print("Finished")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
Reference in New Issue
Block a user