matplotlib

Форк
0
/
cache_zenodo_svg.py 
162 строки · 4.5 Кб
1
import urllib.request
2
from io import BytesIO
3
import os
4
from pathlib import Path
5

6

7
def download_or_cache(url, version):
8
    """
9
    Get bytes from the given url or local cache.
10

11
    Parameters
12
    ----------
13
    url : str
14
        The url to download.
15
    sha : str
16
        The sha256 of the file.
17

18
    Returns
19
    -------
20
    BytesIO
21
        The file loaded into memory.
22
    """
23
    cache_dir = _get_xdg_cache_dir()
24

25
    if cache_dir is not None:  # Try to read from cache.
26
        try:
27
            data = (cache_dir / version).read_bytes()
28
        except OSError:
29
            pass
30
        else:
31
            return BytesIO(data)
32

33
    with urllib.request.urlopen(
34
        urllib.request.Request(url, headers={"User-Agent": ""})
35
    ) as req:
36
        data = req.read()
37

38
    if cache_dir is not None:  # Try to cache the downloaded file.
39
        try:
40
            cache_dir.mkdir(parents=True, exist_ok=True)
41
            with open(cache_dir / version, "xb") as fout:
42
                fout.write(data)
43
        except OSError:
44
            pass
45

46
    return BytesIO(data)
47

48

49
def _get_xdg_cache_dir():
50
    """
51
    Return the XDG cache directory.
52

53
    See
54
    https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
55
    """
56
    cache_dir = os.environ.get("XDG_CACHE_HOME")
57
    if not cache_dir:
58
        cache_dir = os.path.expanduser("~/.cache")
59
        if cache_dir.startswith("~/"):  # Expansion failed.
60
            return None
61
    return Path(cache_dir, "matplotlib")
62

63

64
if __name__ == "__main__":
65
    data = {
66
        "v3.9.2": "13308876",
67
        "v3.9.1": "12652732",
68
        "v3.9.0": "11201097",
69
        "v3.8.4": "10916799",
70
        "v3.8.3": "10661079",
71
        "v3.8.2": "10150955",
72
        "v3.8.1": "10059757",
73
        "v3.8.0": "8347255",
74
        "v3.7.3": "8336761",
75
        "v3.7.2": "8118151",
76
        "v3.7.1": "7697899",
77
        "v3.7.0": "7637593",
78
        "v3.6.3": "7527665",
79
        "v3.6.2": "7275322",
80
        "v3.6.1": "7162185",
81
        "v3.6.0": "7084615",
82
        "v3.5.3": "6982547",
83
        "v3.5.2": "6513224",
84
        "v3.5.1": "5773480",
85
        "v3.5.0": "5706396",
86
        "v3.4.3": "5194481",
87
        "v3.4.2": "4743323",
88
        "v3.4.1": "4649959",
89
        "v3.4.0": "4638398",
90
        "v3.3.4": "4475376",
91
        "v3.3.3": "4268928",
92
        "v3.3.2": "4030140",
93
        "v3.3.1": "3984190",
94
        "v3.3.0": "3948793",
95
        "v3.2.2": "3898017",
96
        "v3.2.1": "3714460",
97
        "v3.2.0": "3695547",
98
        "v3.1.3": "3633844",
99
        "v3.1.2": "3563226",
100
        "v3.1.1": "3264781",
101
        "v3.1.0": "2893252",
102
        "v3.0.3": "2577644",
103
        "v3.0.2": "1482099",
104
        "v3.0.1": "1482098",
105
        "v2.2.5": "3633833",
106
        "v3.0.0": "1420605",
107
        "v2.2.4": "2669103",
108
        "v2.2.3": "1343133",
109
        "v2.2.2": "1202077",
110
        "v2.2.1": "1202050",
111
        "v2.2.0": "1189358",
112
        "v2.1.2": "1154287",
113
        "v2.1.1": "1098480",
114
        "v2.1.0": "1004650",
115
        "v2.0.2": "573577",
116
        "v2.0.1": "570311",
117
        "v2.0.0": "248351",
118
        "v1.5.3": "61948",
119
        "v1.5.2": "56926",
120
        "v1.5.1": "44579",
121
        "v1.5.0": "32914",
122
        "v1.4.3": "15423",
123
        "v1.4.2": "12400",
124
        "v1.4.1": "12287",
125
        "v1.4.0": "11451",
126
    }
127
    doc_dir = Path(__file__).parent.parent.absolute() / "doc"
128
    target_dir = doc_dir / "_static/zenodo_cache"
129
    citing = doc_dir / "project/citing.rst"
130
    target_dir.mkdir(exist_ok=True, parents=True)
131
    header = []
132
    footer = []
133
    with open(citing) as fin:
134
        target = header
135
        for ln in fin:
136
            if target is not None:
137
                target.append(ln.rstrip())
138
            if ln.strip() == ".. START OF AUTOGENERATED":
139
                target.extend(["", ""])
140
                target = None
141
            if ln.strip() == ".. END OF AUTOGENERATED":
142
                target = footer
143
                target.append(ln.rstrip())
144

145
    with open(citing, "w") as fout:
146
        fout.write("\n".join(header))
147
        for version, doi in data.items():
148
            svg_path = target_dir / f"{doi}.svg"
149
            if not svg_path.exists():
150
                url = f"https://zenodo.org/badge/doi/10.5281/zenodo.{doi}.svg"
151
                payload = download_or_cache(url, f"{doi}.svg")
152
                with open(svg_path, "xb") as svgout:
153
                    svgout.write(payload.read())
154
            fout.write(
155
                f"""
156
{version}
157
   .. image:: ../_static/zenodo_cache/{doi}.svg
158
      :target:  https://doi.org/10.5281/zenodo.{doi}"""
159
            )
160
        fout.write("\n\n")
161
        fout.write("\n".join(footer))
162
        fout.write("\n")
163

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.