File: utils.py

package info (click to toggle)
pybik 3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 13,280 kB
  • sloc: python: 11,362; cpp: 5,116; xml: 264; makefile: 50; sh: 2
file content (143 lines) | stat: -rw-r--r-- 5,478 bytes parent folder | download | duplicates (3)
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
# -*- coding: utf-8 -*-

#  Copyright © 2013-2017  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys, os
from glob import glob
from contextlib import suppress


def update_linguas():
    import polib
    min_percent_translated = 20
    cnt_skipped = 0
    with open('po/LINGUAS', 'wt', encoding='utf-8') as linguas:
        po_files = sorted(glob('po/*.po'))
        for po_file in po_files:
            percent_translated = polib.pofile(po_file).percent_translated()
            if percent_translated < min_percent_translated:
                print('skipping po file {!r} ({}%<{}% translated)'.format(
                            po_file, percent_translated, min_percent_translated),
                    file=sys.stderr)
                cnt_skipped += 1
            else:
                print(os.path.splitext(os.path.basename(po_file))[0], file=linguas)
        print('skipped {}/{} po files'.format(cnt_skipped, len(po_files)), file=sys.stderr)
                
def get_linguas():
    with open('po/LINGUAS', 'rt', encoding='utf-8') as linguas:
        return linguas.read().splitlines()
        
def generate_lang_translations():
    from pybiklib.dialogs import get_langname_from_code_func
    langname_from_code = get_langname_from_code_func()
    names = ((code, langname_from_code(code)) for code in get_linguas())
    names = {code: name for code, name in names if name is not None}
    print(names)
    
def generate_all_lang_translations(file=sys.stdout):
    import icu  # to be sure get_langname_from_code_func does not return a fallback function
    from subprocess import Popen, PIPE
    from ast import literal_eval
    from pprint import pformat
    
    processes = []
    env = os.environ.copy()
    for lang in get_linguas():
        env['LC_MESSAGES'] = lang+'.UTF-8'
        script = 'import buildlib.utils as m; m.generate_lang_translations()'
        print(lang, end=' ', flush=True)
        processes.append((lang, Popen(['python3', '-c', script], env=env, stdout=PIPE)))
    print()
    
    langs = {}
    for lang, process in processes:
        print(lang, end=' ', flush=True)
        outstr, unused_err = process.communicate()
        outstr = outstr.strip().decode('utf-8')
        try:
            langs[lang] = literal_eval(outstr)
        except SyntaxError:
            print('code for lang %r:' % lang, repr(outstr))
            raise
    print()
    
    print('# -*- coding: utf-8 -*-', file=file)
    print('# generated file\n', file=file)
    print('languages = (', file=file)
    print(pformat(langs), file=file)
    print(')\n', file=file)
    
def modify_file(filename, subs, count=1):
    from shutil import copymode
    import re
    print('modifying', filename)
    with open(filename, 'rt', encoding='utf-8') as f:
        rtext = f.read()
    wtext = rtext
    for pattern, repl in subs:
        wtext = re.sub(pattern, repl, wtext, count=count, flags=re.MULTILINE)
    if wtext == rtext:
        return False
    tmpfilename = filename+'.tmp'
    with open(tmpfilename, 'xt', encoding='utf-8') as f:
        f.write(wtext)
    copymode(filename, tmpfilename)
    os.rename(tmpfilename, filename)
    return True
        
variants = (
    {'id': 'qtw',  'name': 'QtWidgets (default)',  'group': 'qtvariant',  'type': 'enum'},
    {'id': 'qtq',  'name': 'QtQuick/QML',          'group': 'qtvariant',  'type': 'enum'},
    {'id': 'ogl',  'name': 'OpenGL (default)',     'group': 'glvariant',  'type': 'enum'},
    {'id': 'es2',  'name': 'OpenGLES2',            'group': 'glvariant',  'type': 'enum'},
    {'id': 'd',    'name': 'debug OpenGL/ES',      'group': 'gldebug',    'type': 'bool'},
    {'id': 'os',   'name': 'offscreen',            'group': 'offscreen',  'type': 'bool'},
    {'id': 'all',  'name': 'all variants',                                'type': None},
)

def accepted_variants():
    return {v['id']: v for v in variants}
    
def variant_string():
    return ', '.join('%s (%s)'%(v['id'],v['name']) for v in variants)
    
def group_variants(variant_ids):
    grouped_variants = {}
    for v in variants:
        if v['type'] == None:
            continue
        values, all_values = grouped_variants.setdefault(v['group'], [[], []])
        if v['type'] == 'bool':
            values.append(None)
            all_values.append(None)
        if v['id'] in variant_ids or 'all' in variant_ids:
            values.append(v['id'])
        all_values.append(v['id'])
    # set default enum variants
    for v in variants:
        if v['type'] != 'enum':
            continue
        values, all_values = grouped_variants[v['group']]
        if not values:
            values.append(v['id'])
    for v in variants:
        with suppress(KeyError):
            g = v['group']
            values, all_values = grouped_variants.pop(g)
            yield g, values, all_values