File: commands.py

package info (click to toggle)
sphinx-intl 2.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 340 kB
  • sloc: python: 1,162; makefile: 13
file content (403 lines) | stat: -rw-r--r-- 9,990 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""
sphinx-intl
~~~~~~~~~~~
Sphinx utility that make it easy to translate and to apply translation.

:copyright: Copyright 2019 by Takayuki SHIMIZUKAWA.
:license: BSD, see LICENSE for details.
"""

import re
import os
import warnings
from glob import glob

import click
from sphinx.util.tags import Tags

from . import basic
from . import transifex
from .pycompat import execfile_, relpath

ENVVAR_PREFIX = "SPHINXINTL"


# ==================================
# utility functions


def read_config(path, passed_tags):
    tags = Tags()
    passed_tags = sum(passed_tags, ())
    for tag in passed_tags:
        tags.add(tag)

    namespace = {
        "__file__": os.path.abspath(path),
        "tags": tags,
    }

    olddir = os.getcwd()
    try:
        if not os.path.isfile(path):
            msg = "'%s' is not found (or specify --locale-dir option)." % path
            raise click.BadParameter(msg)
        os.chdir(os.path.dirname(path) or ".")
        execfile_(os.path.basename(path), namespace)
    finally:
        os.chdir(olddir)

    return namespace


def get_lang_dirs(path):
    dirs = [
        relpath(d, path)
        for d in glob(path + "/[a-z]*")
        if os.path.isdir(d) and not d.endswith("pot")
    ]
    return (tuple(dirs),)


# ==================================
# click options


class LanguagesType(click.ParamType):
    name = "languages"
    envvar_list_splitter = ","

    def convert(self, value, param, ctx):
        langs = value.split(",")
        return tuple(langs)


LANGUAGES = LanguagesType()


class TagsType(click.ParamType):
    name = "tags"
    envvar_list_splitter = ","

    def convert(self, value, param, ctx):
        tags = value.split(",")
        return tuple(tags)


TAGS = TagsType()


option_locale_dir = click.option(
    "-d",
    "--locale-dir",
    envvar=ENVVAR_PREFIX + "_LOCALE_DIR",
    type=click.Path(exists=False, file_okay=False),
    default="locales",
    metavar="<DIR>",
    show_default=True,
    help="locale directories that allow comma separated string. This option "
    "override locale_dir in conf.py setting if provided. Default is empty "
    "list.",
)

option_pot_dir = click.option(
    "--pot-dir",
    "-p",
    envvar=ENVVAR_PREFIX + "_POT_DIR",
    type=click.Path(exists=False, file_okay=False),
    metavar="<DIR>",
    show_default=True,
    help="pot files directory which is generated by sphinx. "
    "Default is 'pot' directory under '--locale-dir' path.",
)

option_output_dir = click.option(
    "--output-dir",
    "-o",
    envvar=ENVVAR_PREFIX + "_OUTPUT_DIR",
    type=click.Path(exists=False, file_okay=False),
    metavar="<DIR>",
    show_default=True,
    help="mo files directory where files are written. "
    "Default is to match the '--locale-dir' path.",
)

option_tag = click.option(
    "-t",
    "--tag",
    envvar=ENVVAR_PREFIX + "_TAG",
    type=TAGS,
    metavar="<TAG>",
    show_default=True,
    multiple=True,
    help="Pass tags to conf.py, as same as passed to sphinx-build -t option.",
)

option_language = click.option(
    "-l",
    "--language",
    envvar=ENVVAR_PREFIX + "_LANGUAGE",
    type=LANGUAGES,
    metavar="<LANG>",
    show_default=True,
    multiple=True,
    help="Target language to update po files. Default is ALL.",
)

option_line_width = click.option(
    "-w",
    "--line-width",
    envvar=ENVVAR_PREFIX + "_LINE_WIDTH",
    type=int,
    default=76,
    metavar="<WIDTH>",
    show_default=True,
    multiple=False,
    help="The maximum line width for the po files, 0 or a negative number "
    "disable line wrapping",
)

option_jobs = click.option(
    "-j",
    "--jobs",
    envvar=ENVVAR_PREFIX + "_JOBS",
    type=int,
    default=0,
    metavar="<JOBS>",
    show_default=True,
    multiple=False,
    help="The number of CPUs to use for updates. 0 means all",
)

option_no_obsolete = click.option(
    "--no-obsolete",
    envvar=ENVVAR_PREFIX + "_NO_OBSOLETE",
    is_flag=True,
    default=False,
    help="Remove obsolete #~ messages.",
)

option_transifex_token = click.option(
    "--transifex-token",
    envvar=ENVVAR_PREFIX + "_TRANSIFEX_TOKEN",
    type=str,
    metavar="<TOKEN>",
    required=True,
    help="Your transifex token. (DEPRECATED)",
)

option_transifex_organization_name = click.option(
    "--transifex-organization-name",
    envvar=ENVVAR_PREFIX + "_TRANSIFEX_ORGANIZATION_NAME",
    type=str,
    metavar="<ORGANIZATION-NAME>",
    required=True,
    help="Your transifex organization name.",
)

option_transifex_project_name = click.option(
    "--transifex-project-name",
    envvar=ENVVAR_PREFIX + "_TRANSIFEX_PROJECT_NAME",
    type=str,
    metavar="<PROJECT-NAME>",
    required=True,
    help="Your transifex project name.",
)


# ==================================
# commands


@click.group()
@click.option(
    "-c",
    "--config",
    type=click.Path(exists=True, file_okay=True, dir_okay=False),
    default=None,
    metavar="<FILE>",
    help="Sphinx conf.py file to read a locale directory setting.",
)
@option_tag
@click.pass_context
def main(ctx, config, tag):
    # load conf.py
    ctx.config = config
    if ctx.config is None:
        for c in ("conf.py", "source/conf.py"):
            if os.path.exists(c):
                ctx.config = c
                break

    # for locale_dir
    ctx.locale_dir = None
    if ctx.config:
        cfg = read_config(ctx.config, tag)
        if "locale_dirs" in cfg:
            ctx.locale_dir = os.path.join(
                os.path.dirname(ctx.config), cfg["locale_dirs"][0]
            )

    # for pot_dir
    ctx.pot_dir = None
    for d in ("_build/gettext", "build/gettext", "_build/locale", "build/locale"):
        if os.path.exists(d):
            ctx.pot_dir = d
            break

    # for transifex_project_name
    ctx.transifex_project_name = None
    target = os.path.normpath(".tx/config")
    if os.path.exists(target):
        matched = re.search(r"\[(.*)\..*\]", open(target).read())
        if matched:
            ctx.transifex_project_name = matched.groups()[0]
            click.echo(
                "Project name loaded from .tx/config: {}".format(
                    ctx.transifex_project_name
                )
            )

    ctx.default_map = {
        "update": {
            "locale_dir": ctx.locale_dir,
            "pot_dir": ctx.pot_dir,
        },
        "build": {
            "locale_dir": ctx.locale_dir,
        },
        "stat": {
            "locale_dir": ctx.locale_dir,
        },
        "update-txconfig-resources": {
            "locale_dir": ctx.locale_dir,
            "pot_dir": ctx.pot_dir,
            "transifex_project_name": ctx.transifex_project_name,
        },
    }


@main.command()
@option_locale_dir
@option_pot_dir
@option_language
@option_line_width
@option_no_obsolete
@option_jobs
def update(locale_dir, pot_dir, language, line_width, no_obsolete, jobs):
    """
    Update specified language's po files from pot.

    \b
    For examples:
       sphinx-intl update -l de -l ja
       sphinx-intl update -l de,ja
    """
    if not pot_dir:
        pot_dir = os.path.join(locale_dir, "pot")
    if not os.path.exists(pot_dir):
        msg = (
            "%(pot_dir)r does not exist. Please specify pot directory with "
            "-p option, or preparing your pot files in %(pot_dir)r." % locals()
        )
        raise click.BadParameter(msg, param_hint="pot_dir")
    if not language:
        language = get_lang_dirs(locale_dir)
    languages = sum(language, ())  # flatten
    if not languages:
        msg = (
            "No languages are found. Please specify language with -l "
            "option, or preparing language directories under %(locale_dir)r "
            "directory." % locals()
        )
        raise click.BadParameter(msg, param_hint="language")

    basic.update(
        locale_dir,
        pot_dir,
        languages,
        line_width,
        ignore_obsolete=no_obsolete,
        jobs=jobs,
    )


@main.command()
@option_locale_dir
@option_output_dir
@option_language
def build(locale_dir, output_dir, language):
    """
    Build specified language's po files into mo.
    """
    if not language:
        language = get_lang_dirs(locale_dir)
    languages = sum(language, ())  # flatten

    if not output_dir or (
        os.path.exists(output_dir) and os.path.samefile(locale_dir, output_dir)
    ):
        output_dir = locale_dir

    basic.build(locale_dir, output_dir, languages)


@main.command()
@option_locale_dir
@option_language
def stat(locale_dir, language):
    """
    Print statistics for all po files.
    """
    if not language:
        language = get_lang_dirs(locale_dir)
    languages = sum(language, ())  # flatten
    basic.stat(locale_dir, languages)


@main.command("create-transifexrc")
@option_transifex_token
def create_transifexrc(transifex_token):
    """
    Create `$HOME/.transifexrc`  (deprecated)
    """
    warnings.filterwarnings("default", category=DeprecationWarning)
    warnings.warn(
        (
            "create-transifexrc command and SPHINXINTL_TRANSIFEX_TOKEN "
            "will be deprecated. Please use TX_TOKEN environment variable instead."
        ),
        category=DeprecationWarning,
    )
    transifex.create_transifexrc(transifex_token)


@main.command("create-txconfig")
def create_txconfig():
    """
    Create `./.tx/config`
    """
    transifex.create_txconfig()


@main.command("update-txconfig-resources")
@option_transifex_organization_name
@option_transifex_project_name
@option_locale_dir
@option_pot_dir
def update_txconfig_resources(
    transifex_organization_name, transifex_project_name, locale_dir, pot_dir
):
    """
    Update resource sections of `./.tx/config`.
    """
    if not pot_dir:
        pot_dir = os.path.join(locale_dir, "pot")

    transifex.update_txconfig_resources(
        transifex_organization_name, transifex_project_name, locale_dir, pot_dir
    )


if __name__ == "__main__":
    main(auto_envvar_prefix=ENVVAR_PREFIX)