|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import glob |
| 3 | +import json |
| 4 | +import os |
| 5 | +import re |
| 6 | +import sys |
| 7 | +import urllib.request |
| 8 | + |
| 9 | + |
| 10 | +def list_resources(token, project): |
| 11 | + auth_handler = urllib.request.HTTPBasicAuthHandler() |
| 12 | + auth_handler.add_password( |
| 13 | + realm="api", uri="https://api.transifex.com/", user="api", passwd=token |
| 14 | + ) |
| 15 | + opener = urllib.request.build_opener(auth_handler) |
| 16 | + urllib.request.install_opener(opener) |
| 17 | + next_ = ( |
| 18 | + "https://api.transifex.com/organizations/python-doc/projects/" |
| 19 | + + project |
| 20 | + + "/resources/" |
| 21 | + ) |
| 22 | + resources = [] |
| 23 | + while True: |
| 24 | + resp = urllib.request.urlopen(next_) |
| 25 | + result = json.loads(resp.read().decode("utf-8")) |
| 26 | + resources.extend([i["slug"] for i in result]) |
| 27 | + link = re.findall('<([^<]*)>; rel="next"', resp.getheader("Link") or "") |
| 28 | + if not link: |
| 29 | + break |
| 30 | + next_ = link[0] |
| 31 | + return resources |
| 32 | + |
| 33 | + |
| 34 | +def render_config(doc_dir, project, resources): |
| 35 | + os.chdir(doc_dir) |
| 36 | + tpl = """ |
| 37 | +
|
| 38 | +[{project}.{resource}] |
| 39 | +trans.zh_CN = {filename} |
| 40 | +source_lang = en |
| 41 | +type = PO""" |
| 42 | + conf = """[main] |
| 43 | +host = https://www.transifex.com""" |
| 44 | + for resource in sorted(resources): |
| 45 | + if resource == "glossary_": |
| 46 | + filename = "glossary.po" |
| 47 | + elif resource == "sphinx": |
| 48 | + filename = "sphinx.po" |
| 49 | + else: |
| 50 | + pattern = resource.replace("--", "/").replace("_", "?") |
| 51 | + matches = glob.glob(pattern + ".rst") |
| 52 | + if len(matches) == 0: |
| 53 | + print("missing", resource, file=sys.stderr) |
| 54 | + continue |
| 55 | + elif len(matches) == 1: |
| 56 | + filename = matches[0].replace(".rst", ".po") |
| 57 | + else: |
| 58 | + print("multi match", resource, pattern, matches, file=sys.stderr) |
| 59 | + conf += tpl.format(project=project, resource=resource, filename=filename) |
| 60 | + return conf |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + import argparse |
| 65 | + |
| 66 | + parser = argparse.ArgumentParser() |
| 67 | + parser.add_argument("--token") |
| 68 | + parser.add_argument("--project") |
| 69 | + parser.add_argument("--doc-dir") |
| 70 | + args = parser.parse_args() |
| 71 | + |
| 72 | + resources = list_resources(args.token, args.project) |
| 73 | + conf = render_config(args.doc_dir, args.project, resources) |
| 74 | + print(conf) |
| 75 | + |
| 76 | +# vim: set et ts=4 sw=4 sts=4: |
0 commit comments