1# Copyright 2016 The Meson development team
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6
7#     http://www.apache.org/licenses/LICENSE-2.0
8
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import os
16import shutil
17import argparse
18import subprocess
19from . import destdir_join
20
21parser = argparse.ArgumentParser()
22parser.add_argument('command')
23parser.add_argument('--pkgname', default='')
24parser.add_argument('--datadirs', default='')
25parser.add_argument('--langs', default='')
26parser.add_argument('--localedir', default='')
27parser.add_argument('--subdir', default='')
28parser.add_argument('--extra-args', default='')
29
30def read_linguas(src_sub):
31    # Syntax of this file is documented here:
32    # https://www.gnu.org/software/gettext/manual/html_node/po_002fLINGUAS.html
33    linguas = os.path.join(src_sub, 'LINGUAS')
34    try:
35        langs = []
36        with open(linguas) as f:
37            for line in f:
38                line = line.strip()
39                if line and not line.startswith('#'):
40                    langs += line.split()
41        return langs
42    except (FileNotFoundError, PermissionError):
43        print('Could not find file LINGUAS in {}'.format(src_sub))
44        return []
45
46def run_potgen(src_sub, pkgname, datadirs, args):
47    listfile = os.path.join(src_sub, 'POTFILES.in')
48    if not os.path.exists(listfile):
49        listfile = os.path.join(src_sub, 'POTFILES')
50        if not os.path.exists(listfile):
51            print('Could not find file POTFILES in %s' % src_sub)
52            return 1
53
54    child_env = os.environ.copy()
55    if datadirs:
56        child_env['GETTEXTDATADIRS'] = datadirs
57
58    ofile = os.path.join(src_sub, pkgname + '.pot')
59    return subprocess.call(['xgettext', '--package-name=' + pkgname, '-p', src_sub, '-f', listfile,
60                            '-D', os.environ['MESON_SOURCE_ROOT'], '-k_', '-o', ofile] + args,
61                           env=child_env)
62
63def gen_gmo(src_sub, bld_sub, langs):
64    for l in langs:
65        subprocess.check_call(['msgfmt', os.path.join(src_sub, l + '.po'),
66                               '-o', os.path.join(bld_sub, l + '.gmo')])
67    return 0
68
69def update_po(src_sub, pkgname, langs):
70    potfile = os.path.join(src_sub, pkgname + '.pot')
71    for l in langs:
72        pofile = os.path.join(src_sub, l + '.po')
73        if os.path.exists(pofile):
74            subprocess.check_call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
75        else:
76            subprocess.check_call(['msginit', '--input', potfile, '--output-file', pofile, '--locale', l, '--no-translator'])
77    return 0
78
79def do_install(src_sub, bld_sub, dest, pkgname, langs):
80    for l in langs:
81        srcfile = os.path.join(bld_sub, l + '.gmo')
82        outfile = os.path.join(dest, l, 'LC_MESSAGES',
83                               pkgname + '.mo')
84        tempfile = outfile + '.tmp'
85        os.makedirs(os.path.dirname(outfile), exist_ok=True)
86        shutil.copyfile(srcfile, tempfile)
87        shutil.copystat(srcfile, tempfile)
88        os.replace(tempfile, outfile)
89        print('Installing %s to %s' % (srcfile, outfile))
90    return 0
91
92def run(args):
93    options = parser.parse_args(args)
94    subcmd = options.command
95    langs = options.langs.split('@@') if options.langs else None
96    extra_args = options.extra_args.split('@@') if options.extra_args else []
97    subdir = os.environ.get('MESON_SUBDIR', '')
98    if options.subdir:
99        subdir = options.subdir
100    src_sub = os.path.join(os.environ['MESON_SOURCE_ROOT'], subdir)
101    bld_sub = os.path.join(os.environ['MESON_BUILD_ROOT'], subdir)
102
103    if not langs:
104        langs = read_linguas(src_sub)
105
106    if subcmd == 'pot':
107        return run_potgen(src_sub, options.pkgname, options.datadirs, extra_args)
108    elif subcmd == 'gen_gmo':
109        return gen_gmo(src_sub, bld_sub, langs)
110    elif subcmd == 'update_po':
111        if run_potgen(src_sub, options.pkgname, options.datadirs, extra_args) != 0:
112            return 1
113        return update_po(src_sub, options.pkgname, langs)
114    elif subcmd == 'install':
115        destdir = os.environ.get('DESTDIR', '')
116        dest = destdir_join(destdir, os.path.join(os.environ['MESON_INSTALL_PREFIX'],
117                                                  options.localedir))
118        if gen_gmo(src_sub, bld_sub, langs) != 0:
119            return 1
120        do_install(src_sub, bld_sub, dest, options.pkgname, langs)
121    else:
122        print('Unknown subcommand.')
123        return 1
124