forked from linuxmint/cinnamon-spices-actions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cinnamon-spices-makepot
executable file
·181 lines (168 loc) · 6.95 KB
/
cinnamon-spices-makepot
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
#!/usr/bin/python3
import argparse
import json
import os
import subprocess
import sys
from glob import glob
from gi.repository import GLib
GROUP = "Nemo Action"
def parse_args():
"""
Get command line arguments and process translation actions
"""
parser = argparse.ArgumentParser()
parser.description = 'Arguments for cinnamon-spices-makepot'
parser.add_argument('-i', '--install', action='store_true',
help='Install translation files locally for testing')
parser.add_argument('-r', '--remove', action='store_true',
help='The opposite of install, removes local '
'translations.')
parser.add_argument('-a', '--all', action='store_true',
help='Create or update translation templates for all '
'Spices')
parser.add_argument('uuid', type=str, metavar='UUID', nargs='?',
help='the UUID of the Spice')
args = parser.parse_args()
if args.uuid and args.uuid.endswith('/'):
args.uuid = args.uuid.replace('/', '')
if args.all and not args.uuid:
for file_path in os.listdir("."):
if os.path.isdir(file_path) and not file_path.startswith("."):
if args.install:
install_po(file_path, True)
elif args.remove:
remove_po(file_path, True)
else:
make_pot(file_path, True)
elif args.install and args.remove:
print('Only -i/--install OR -r/--remove may be specified. Not both.')
sys.exit(1)
elif args.install and args.uuid:
install_po(args.uuid)
elif args.remove and args.uuid:
remove_po(args.uuid)
elif args.uuid:
make_pot(args.uuid)
else:
parser.print_help()
def install_po(uuid: str, _all: bool = False):
"""
Install translation files locally from the po directory of the UUID
"""
uuid_path = f'{uuid}/files/{uuid}'
try:
contents = os.listdir(uuid_path)
except FileNotFoundError:
print(f'Translations not found for: {uuid}')
if not _all:
sys.exit(1)
home = os.path.expanduser("~")
locale_inst = f'{home}/.local/share/locale'
if 'po' in contents:
po_dir = f'{uuid_path}/po'
for file in os.listdir(po_dir):
if file.endswith('.po'):
lang = file.split(".")[0]
locale_dir = os.path.join(locale_inst, lang, 'LC_MESSAGES')
os.makedirs(locale_dir, mode=0o755, exist_ok=True)
subprocess.run(['msgfmt', '-c', os.path.join(po_dir, file),
'-o', os.path.join(locale_dir, f'{uuid}.mo')],
check=True)
def remove_po(uuid: str, _all: bool = False):
"""
Remove local translation files for the UUID
"""
home = os.path.expanduser("~")
locale_inst = f'{home}/.local/share/locale'
uuid_mo_list = glob(f'{locale_inst}/**/{uuid}.mo', recursive=True)
if not uuid_mo_list:
print(f'No translation files found for: {uuid}')
if not _all:
sys.exit(1)
for uuid_mo_file in uuid_mo_list:
os.remove(uuid_mo_file)
def make_pot(uuid: str, _all: bool = False):
"""
Make the translation template file for the UUID
"""
if len(sys.argv) > 1 and not _all:
_pwd = sys.argv[1]
else:
_pwd = os.getcwd()
uuid_path = uuid if _all else ''
sub_dir = f'{_pwd}/{uuid}'
action_file = glob(os.path.join(_pwd, uuid_path, "*.nemo_action.in"))
if _all:
os.chdir(sub_dir)
if len(action_file) > 0:
output_string = ''
for file_name in action_file:
keyfile = GLib.KeyFile.new()
if keyfile.load_from_file(file_name, GLib.KeyFileFlags.NONE):
if keyfile.has_group(GROUP):
header_file = action_file[0].split('/')[-1]
try:
name = keyfile.get_string(GROUP, "_Name")
name_pot = f'\n#. {header_file}->Name\nmsgid "{name}"\nmsgstr ""\n'
output_string += (name_pot)
except GLib.GError:
name = None
try:
comment = keyfile.get_string(GROUP, "_Comment")
comment_line = f'\n#. {header_file}->Comment\nmsgid "{comment}"\nmsgstr ""\n'
output_string += (comment_line)
except GLib.GError:
comment = None
po_dir = f'files/{uuid}/po' if _all else f'{_pwd}/files/{uuid}/po'
return_dir = _pwd if _all else '../../..'
uuid_dir = f'{_pwd}/{uuid_path}/files/{uuid}'.replace('//', '/')
pot_file = uuid + '.pot'
outfile = os.path.join(po_dir, pot_file)
if os.path.exists(outfile):
os.remove(outfile)
elif not os.path.exists(po_dir):
os.mkdir(po_dir)
input_dir = sub_dir if _all else _pwd
subprocess.run(["cinnamon-xlet-makepot", "-o", outfile, input_dir],
check=True)
os.chdir(uuid_dir)
pot_path = f'po/{pot_file}'
shell_list = glob('**/*.sh', recursive=True)
for shell_file in shell_list:
subprocess.run(["xgettext", "-jL", "Shell", "-o", pot_path,
shell_file], stderr=subprocess.DEVNULL, check=True)
os.chdir(return_dir)
metadata_file = f'{uuid}/files/{uuid}/metadata.json'
try:
with open(metadata_file, encoding='utf-8') as meta:
metadata = json.load(meta)
version = str(metadata['version'])
except (FileNotFoundError, KeyError):
print(f"{uuid}: metadata.json or version not found")
version = "1.0"
if _all:
outfile = f'{uuid}/{outfile}'
with open(outfile, 'a', encoding='utf-8') as output_file:
output_file.write(output_string)
address = 'https://github.com/linuxmint/cinnamon-spices-actions/issues'
subprocess.run(["xgettext", "-w", "79", "--package-name", uuid,
"--foreign-user", "--msgid-bugs-address", address,
"--package-version", version, "-o", outfile, outfile],
check=True)
po_list = glob(f'{uuid}/**/*.po', recursive=True)
for po_file in po_list:
*po_dir_list, po_ext = po_file.split('/')
po_dir_str = '/'.join(po_dir_list)
if not os.getcwd().endswith(po_dir_str):
os.chdir(po_dir_str)
po_lang = po_ext.split('.')[0]
subprocess.run(["intltool-update", "-g", uuid, "-d", po_lang],
check=True)
subprocess.run(["msgattrib", "--no-obsolete", "-w", "79", "-o",
po_ext, po_ext],
check=True)
if _all:
os.chdir(return_dir)
if __name__ == "__main__":
parse_args()