Skip to content

Instantly share code, notes, and snippets.

@Chocimier
Last active October 3, 2016 19:48
Show Gist options
  • Save Chocimier/f8cf6ce3215009df57c1 to your computer and use it in GitHub Desktop.
Save Chocimier/f8cf6ce3215009df57c1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Fixes desktop and ts files from Transifex"""
import os
import re
import shutil
import sys
class DesktopProcessor:
"""Processes localized .desktop files"""
language_dictionary = {}
def set_mapping(self, dictionary):
"""Sets dictionary of language codes to be replaced with other code
in process(...) result file."""
self.language_dictionary = dictionary
def _format_line(self, key, language, value):
"""Formats desktop file's line"""
if language:
return '{}[{}]={}'.format(key, (self.language_dictionary[language] if language in self.language_dictionary else language), value)
else:
return '{}={}'.format(key, value)
def process(self, output_filepath='joined.desktop', input_directory=os.getcwd()):
"""Merges multiple localized .desktop files into one.
Works good only if there is one group[1] in file.
output_filepath is path of result file
input_directory is path of directory with input files
[1] https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#group-header
"""
header = ''
sorted_keys = []
translations = {}
for name in os.listdir(input_directory):
if (not name.endswith('.desktop')) or name == output_filepath:
continue
file_ = open(os.path.join(input_directory, name))
for line in file_.readlines():
if line.startswith('['):
header = line
continue
elif line.startswith('#') or line.strip() == '':
continue
local_key, value = line.split('=')
key, language = (local_key.split('[') + [''])[0:2]
language = language.strip(']')
if key in translations:
if line not in translations[key]:
translations[key].append(self._format_line(key, language, value))
else:
sorted_keys.append(key)
translations[key] = [self._format_line(key, language, value)]
file_.close()
file_ = open(output_filepath, 'w')
file_.write(header)
for key in sorted_keys:
translations[key].sort()
for line in translations[key]:
file_.write(line)
file_.close()
def ts_rename(source, target, dictionary, prefix, postfix):
"""Copies ts files from source to target with names fixed as in dictionary"""
for filename in os.listdir(source):
regex = re.compile(re.escape(prefix) + '(.*)' + re.escape(postfix))
if not regex.match(filename):
continue
language = regex.match(filename).group(1)
language = dictionary[language] if language in dictionary else language
fixed_filename = prefix + language + postfix
shutil.copy(os.path.join(source, filename), os.path.join(target, fixed_filename))
if __name__ == "__main__":
try:
source, target = sys.argv[1:3]
except ValueError:
print('Usage: python {} source_dir target_dir'.format(sys.args[0]))
sys.exit(1)
dictionary = {
'zh_CN.GB2312': 'zh_CN',
'sr@Ijekavian': 'sr@ijekavian'
}
processor = DesktopProcessor()
processor.set_mapping(dictionary)
processor.process(os.path.join(target, 'otter-browser.desktop'), source)
ts_rename(source, os.path.join(target, 'resources', 'translations'), dictionary, 'otter-browser_', '.ts')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment