| 1 |
#!/usr/bin/python3 |
| 2 |
|
| 3 |
import os |
| 4 |
import json |
| 5 |
import subprocess |
| 6 |
import collections |
| 7 |
import argparse |
| 8 |
from datetime import datetime |
| 9 |
import pytz |
| 10 |
|
| 11 |
LOCALE_DIR = os.path.join(os.path.expanduser('~'), '.local/share/locale') |
| 12 |
|
| 13 |
USAGE_DESCRIPTION = """\ |
| 14 |
Parses files in an applet, desklet or extension's directories, \ |
| 15 |
extracts translatable strings, and then generates a .pot file for them. |
| 16 |
""" |
| 17 |
|
| 18 |
USAGE_EPILOG = """\ |
| 19 |
For example: |
| 20 |
cinnamon-xlet-makepot [email protected]/ |
| 21 |
|
| 22 |
Will generate a file called [email protected], in the directory \ |
| 23 |
[email protected]/po/ which contains all of the strings that need to be \ |
| 24 |
translated. Translators can then use this pot file to generate .po \ |
| 25 |
files which contain translations for the extracted strings. |
| 26 |
""" |
| 27 |
|
| 28 |
try: |
| 29 |
import polib |
| 30 |
except Exception: |
| 31 |
print("""\ |
| 32 |
|
| 33 |
Module "polib" not available. |
| 34 |
|
| 35 |
You will need to install this module using your distribution's package manager |
| 36 |
(in debian-based systems "apt-get install python3-polib") |
| 37 |
""") |
| 38 |
quit() |
| 39 |
|
| 40 |
|
| 41 |
def scan_json(dir, pot_path): |
| 42 |
append = os.path.exists(pot_path) |
| 43 |
if append: |
| 44 |
pot_file = polib.pofile(pot_path) |
| 45 |
pot_file.metadata['Content-Type'] = 'text/plain; charset=UTF-8' |
| 46 |
else: |
| 47 |
pot_file = polib.POFile() |
| 48 |
pot_file.header = 'SOME DESCRIPTIVE TITLE.\n' \ |
| 49 |
'Copyright (C) YEAR THE PACKAGE\'S COPYRIGHT HOLDER\n' \ |
| 50 |
'This file is distributed under the same license as the PACKAGE package.\n' \ |
| 51 |
'FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n' \ |
| 52 |
'\n' \ |
| 53 |
', fuzzy' |
| 54 |
pot_file.metadata = { |
| 55 |
'Project-Id-Version': 'PACKAGE VERSION', |
| 56 |
'Report-Msgid-Bugs-To': '', |
| 57 |
'POT-Creation-Date': '%s' % datetime.now(pytz.utc).strftime("%Y-%m-%d %H:%M%z"), |
| 58 |
'PO-Revision-Date': 'YEAR-MO-DA HO:MI+ZONE', |
| 59 |
'Last-Translator': 'FULL NAME <EMAIL@ADDRESS>', |
| 60 |
'Language-Team': 'LANGUAGE <[email protected]>', |
| 61 |
'Language': '', |
| 62 |
'MIME-Version': '1.0', |
| 63 |
'Content-Type': 'text/plain; charset=UTF-8', |
| 64 |
'Content-Transfer-Encoding': '8bit', |
| 65 |
} |
| 66 |
|
| 67 |
for root, dirs, files in os.walk(dir): |
| 68 |
rel_root = os.path.relpath(root) |
| 69 |
for file in sorted(files): |
| 70 |
if rel_root == '.': |
| 71 |
rel_path = file |
| 72 |
else: |
| 73 |
rel_path = os.path.join(rel_root, file) |
| 74 |
if file == 'settings-schema.json': |
| 75 |
fp = open(os.path.join(root, file)) |
| 76 |
data = json.load(fp, object_pairs_hook=collections.OrderedDict) |
| 77 |
fp.close() |
| 78 |
extract_settings_strings(data, rel_path.replace('/', '->'), pot_file) |
| 79 |
elif file == 'metadata.json': |
| 80 |
fp = open(os.path.join(root, file)) |
| 81 |
data = json.load(fp, object_pairs_hook=collections.OrderedDict) |
| 82 |
fp.close() |
| 83 |
extract_metadata_strings(data, rel_path.replace('/', '->'), pot_file) |
| 84 |
|
| 85 |
if append: |
| 86 |
pot_file.save(pot_path) |
| 87 |
else: |
| 88 |
pot_file.save(fpath=pot_path) |
| 89 |
|
| 90 |
|
| 91 |
def extract_settings_strings(data, dir, pot_file, parent=""): |
| 92 |
for key in data.keys(): |
| 93 |
if parent != "": |
| 94 |
if key in ("description", "tooltip", "units", "title"): |
| 95 |
comment = "%s->%s->%s" % (dir, parent, key) |
| 96 |
save_entry(data[key], comment, pot_file) |
| 97 |
elif key in "options": |
| 98 |
opt_data = data[key] |
| 99 |
for option in opt_data.keys(): |
| 100 |
if opt_data[option] == "custom": |
| 101 |
continue |
| 102 |
comment = "%s->%s->%s" % (dir, parent, key) |
| 103 |
save_entry(option, comment, pot_file) |
| 104 |
elif key == "columns": |
| 105 |
columns = data[key] |
| 106 |
for i, col in enumerate(columns): |
| 107 |
for col_key in col: |
| 108 |
if col_key in ("title", "units"): |
| 109 |
comment = "%s->%s->columns->%s" % (dir, parent, col_key) |
| 110 |
save_entry(col[col_key], comment, pot_file) |
| 111 |
try: |
| 112 |
extract_settings_strings(data[key], dir, pot_file, key) |
| 113 |
except AttributeError: |
| 114 |
pass |
| 115 |
|
| 116 |
|
| 117 |
def extract_metadata_strings(data, dir, pot_file): |
| 118 |
for key in data: |
| 119 |
if key in ("name", "description", "comments"): |
| 120 |
comment = "%s->%s" % (dir, key) |
| 121 |
save_entry(data[key], comment, pot_file) |
| 122 |
elif key == "contributors": |
| 123 |
comment = "%s->%s" % (dir, key) |
| 124 |
|
| 125 |
values = data[key] |
| 126 |
if isinstance(values, str): |
| 127 |
values = values.split(",") |
| 128 |
|
| 129 |
for value in values: |
| 130 |
save_entry(value.strip(), comment, pot_file) |
| 131 |
|
| 132 |
|
| 133 |
def save_entry(msgid, comment, pot_file): |
| 134 |
if not isinstance(msgid, str): |
| 135 |
print("Warning: expected string and got %s of type %s instead" % (str(msgid), type(msgid))) |
| 136 |
return |
| 137 |
|
| 138 |
if not msgid.strip(): |
| 139 |
return |
| 140 |
|
| 141 |
entry = pot_file.find(msgid) |
| 142 |
if entry: |
| 143 |
if comment not in entry.comment: |
| 144 |
if entry.comment: |
| 145 |
entry.comment += "\n" |
| 146 |
entry.comment += comment |
| 147 |
else: |
| 148 |
entry = polib.POEntry(msgid=msgid, comment=comment) |
| 149 |
pot_file.append(entry) |
| 150 |
|
| 151 |
|
| 152 |
def remove_empty_folders(path): |
| 153 |
if not os.path.isdir(path): |
| 154 |
return |
| 155 |
|
| 156 |
# remove empty subfolders |
| 157 |
files = os.listdir(path) |
| 158 |
if len(files): |
| 159 |
for f in sorted(files): |
| 160 |
fullpath = os.path.join(path, f) |
| 161 |
if os.path.isdir(fullpath): |
| 162 |
remove_empty_folders(fullpath) |
| 163 |
|
| 164 |
# if folder empty, delete it |
| 165 |
files = os.listdir(path) |
| 166 |
if len(files) == 0: |
| 167 |
print('Removing empty folder:', path) |
| 168 |
os.rmdir(path) |
| 169 |
|
| 170 |
|
| 171 |
def do_install(uuid, dir): |
| 172 |
podir = os.path.join(dir, "po") |
| 173 |
files_installed = 0 |
| 174 |
for root, subFolders, files in os.walk(podir): |
| 175 |
for file in sorted(files): |
| 176 |
locale_name, ext = os.path.splitext(file) |
| 177 |
if ext == '.po': |
| 178 |
lang_locale_dir = os.path.join(LOCALE_DIR, locale_name, 'LC_MESSAGES') |
| 179 |
os.makedirs(lang_locale_dir, mode=0o755, exist_ok=True) |
| 180 |
subprocess.call(["msgfmt", "-c", os.path.join(root, file), "-o", os.path.join(lang_locale_dir, '%s.mo' % uuid)]) |
| 181 |
files_installed += 1 |
| 182 |
if files_installed == 0: |
| 183 |
print('Nothing to install') |
| 184 |
else: |
| 185 |
print('installed %i files' % files_installed) |
| 186 |
|
| 187 |
|
| 188 |
def do_remove(uuid): |
| 189 |
files_removed = 0 |
| 190 |
if os.path.exists(LOCALE_DIR): |
| 191 |
locale_names = os.listdir(LOCALE_DIR) |
| 192 |
for locale_name in locale_names: |
| 193 |
lang_locale_dir = os.path.join(LOCALE_DIR, locale_name) |
| 194 |
mo_file = os.path.join(lang_locale_dir, 'LC_MESSAGES', "%s.mo" % uuid) |
| 195 |
if os.path.isfile(mo_file): |
| 196 |
os.remove(mo_file) |
| 197 |
files_removed += 1 |
| 198 |
remove_empty_folders(lang_locale_dir) |
| 199 |
if files_removed == 0: |
| 200 |
print("Nothing to remove") |
| 201 |
else: |
| 202 |
print('removed %i files' % files_removed) |
| 203 |
|
| 204 |
|
| 205 |
def scan_xlet(): |
| 206 |
parser = argparse.ArgumentParser(description=USAGE_DESCRIPTION, epilog=USAGE_EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 207 |
parser.add_argument('-j', '--skip-js', action='store_false', dest='js', default=True, |
| 208 |
help='If this option is not included, javascript files will be scanned for translatable strings.') |
| 209 |
parser.add_argument('-p', '--skip-python', action='store_false', dest='python', default=True, |
| 210 |
help='If this option is not included, python files will be scanned for translatable strings.') |
| 211 |
parser.add_argument('-i', '--install', action='store_true', dest='install', default=False, |
| 212 |
help=('Compiles and installs any .po files contained in a po folder to the system locale store. ' |
| 213 |
'Use this option to test your translations locally before uploading to Spices. ' |
| 214 |
'It will use the applet, desklet, or extension UUID as the translation domain.')) |
| 215 |
parser.add_argument('-r', '--remove', action='store_true', dest='remove', default=False, |
| 216 |
help=('The opposite of install, removes translations from the store. Again, it uses the UUID ' |
| 217 |
'to find the correct files to remove.')) |
| 218 |
parser.add_argument('-k', '--keyword', dest='keyword', default='_', |
| 219 |
help='Change the variable name gettext is assigned to in your files. The default is _.') |
| 220 |
parser.add_argument('-o', '--potfile', dest='out_file', default=None, |
| 221 |
help=('Use this option to specify the location for the generated .pot file. By default ' |
| 222 |
'<uuid>/po/<uuid>.pot is used. This is where translators are expecting to find the pot ' |
| 223 |
'file, so you should only use this option if you want the pot file elsewhere for your own use.')) |
| 224 |
parser.add_argument('-m', '--makepot', action='store_true', dest='makepot', default=False, |
| 225 |
help=('This is used by makepot to tell this script not to remove the existing pot file.')) |
| 226 |
parser.add_argument('dir', help='the path to the applet/desklet/extension directory') |
| 227 |
|
| 228 |
args = parser.parse_args() |
| 229 |
|
| 230 |
dir = os.path.abspath(args.dir) |
| 231 |
if not os.path.exists(dir): |
| 232 |
print('%s does not exist' % dir) |
| 233 |
quit() |
| 234 |
|
| 235 |
uuid = os.path.basename(dir) |
| 236 |
|
| 237 |
if os.path.exists(os.path.join(dir, 'files', uuid)): |
| 238 |
dir = os.path.join(dir, 'files', uuid) |
| 239 |
|
| 240 |
if args.install: |
| 241 |
do_install(uuid, dir) |
| 242 |
quit() |
| 243 |
|
| 244 |
if args.remove: |
| 245 |
do_remove(uuid) |
| 246 |
quit() |
| 247 |
|
| 248 |
if args.out_file is not None: |
| 249 |
pot_path = os.path.abspath(args.out_file) |
| 250 |
else: |
| 251 |
pot_path = os.path.join(dir, 'po', uuid + '.pot') |
| 252 |
|
| 253 |
pwd = os.getcwd() |
| 254 |
os.chdir(dir) |
| 255 |
if args.js or args.python: |
| 256 |
try: |
| 257 |
subprocess.check_output(["xgettext", "--version"]) |
| 258 |
except OSError: |
| 259 |
print("xgettext not found, you may need to install the gettext package") |
| 260 |
quit() |
| 261 |
|
| 262 |
os.makedirs(os.path.dirname(pot_path), mode=0o755, exist_ok=True) |
| 263 |
|
| 264 |
pot_exists = False |
| 265 |
if os.path.exists(pot_path) and not args.makepot: |
| 266 |
os.remove(pot_path) |
| 267 |
|
| 268 |
if args.js: |
| 269 |
print("Scanning JavaScript files...") |
| 270 |
|
| 271 |
js_files = [] |
| 272 |
for root, dirs, files in os.walk(dir): |
| 273 |
rel_root = os.path.relpath(root) |
| 274 |
js_files += [os.path.join(rel_root, file) for file in sorted(files) if file.endswith('.js')] |
| 275 |
if len(js_files) == 0: |
| 276 |
print('none found') |
| 277 |
else: |
| 278 |
print('found %i file(s)\n' % len(js_files)) |
| 279 |
command_args = [ |
| 280 |
'xgettext', |
| 281 |
'--language=JavaScript', |
| 282 |
'--from-code=UTF-8', |
| 283 |
'--keyword=%s' % args.keyword, |
| 284 |
'--output=%s' % pot_path |
| 285 |
] |
| 286 |
command_args += js_files |
| 287 |
subprocess.run(command_args) |
| 288 |
pot_exists = os.path.exists(pot_path) |
| 289 |
|
| 290 |
if args.python: |
| 291 |
print("Scanning for python files...") |
| 292 |
|
| 293 |
py_files = [] |
| 294 |
for root, dirs, files in os.walk(dir): |
| 295 |
rel_root = os.path.relpath(root) |
| 296 |
py_files += [os.path.join(rel_root, file) for file in sorted(files) if file.endswith('.py')] |
| 297 |
if len(py_files) == 0: |
| 298 |
print('none found') |
| 299 |
else: |
| 300 |
print('found %i file(s)\n' % len(py_files)) |
| 301 |
command_args = [ |
| 302 |
'xgettext', |
| 303 |
'--language=Python', |
| 304 |
'--from-code=UTF-8', |
| 305 |
'--keyword=%s' % args.keyword, |
| 306 |
'--output=%s' % pot_path |
| 307 |
] |
| 308 |
if pot_exists: |
| 309 |
command_args.append('-j') |
| 310 |
command_args += py_files |
| 311 |
subprocess.run(command_args) |
| 312 |
|
| 313 |
print("Scanning metadata.json and settings-schema.json...") |
| 314 |
scan_json(dir, pot_path) |
| 315 |
|
| 316 |
os.chdir(pwd) |
| 317 |
|
| 318 |
print("Extraction complete") |
| 319 |
quit() |
| 320 |
|
| 321 |
|
| 322 |
if __name__ == "__main__": |
| 323 |
scan_xlet() |