aboutsummaryrefslogtreecommitdiffstats
path: root/desktop/desktoppo.py
blob: ed6dd98d10a63bf7d099e6c0cc79b6d9ff8fbb8b (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import errno, glob, polib, re, os, getopt, sys
from time import strftime

def usage():
    print '\nUsage: python %s [OPTION]' %os.path.basename(sys.argv[0])
    print '       generate pot catalogs and updates po files for desktop resources in the specified directory'
    print 'Options: -h, --help                              : usage'
    print '         -d <directory>, --directory <directory> : directory with desktop files'
    sys.exit(2)
try:
    opts, args = getopt.getopt(sys.argv[1:], "hd:", ["help", "directory="])
except getopt.GetoptError:
    usage() # print help information and exit

directory='.'
for o,a in opts:
    if o in ("-h", "--help"):
        usage()
    if o in ("-d", "--directory"):
        directory=a

directory = directory.rstrip('/')

if (directory != '') and (os.path.isdir(directory) == False):
    sys.exit('Specified directory does not exist')

# Find all desktop files
files = []
for rootdir, dirnames, filenames in os.walk(directory):
    files.extend(glob.glob(rootdir + "/*.desktop"))

# Define Templates and po directory name
messagetemplate='(?<=\n)Name=.*?\n|Comment=.*?\n'
mpattern=re.compile(messagetemplate,re.DOTALL)
translationtemplate='(?<=\n)Name\[.*?\n|Comment\[.*?\n'
tpattern=re.compile(translationtemplate,re.DOTALL)
podir = 'po'

# Write POT file
pot = polib.POFile('',check_for_duplicates=True)
potcreationtime = strftime('%Y-%m-%d %H:%M%z')
pot.metadata = {
  'Project-Id-Version': 'Mageia desktop files translation',
  'Report-Msgid-Bugs-To': 'i18n-discuss@ml.mageia.org',
  'POT-Creation-Date': potcreationtime,
  'PO-Revision-Date': 'YEAR-MO-DA HO:MI+ZONE',
  'Last-Translator': 'FULL NAME <EMAIL@ADDRESS>',
  'Language-Team': 'LANGUAGE <LL@li.org>',
  'MIME-Version': '1.0',
  'Content-Type': 'text/plain; charset=UTF-8',
  'Content-Transfer-Encoding': '8bit',
  }

for langfile in files:
  langfiledir = langfile.replace('.desktop', '')
  langfilename = langfiledir.rpartition('/')[2]
  # Create localization directories if needed
  try:
    os.makedirs(podir)
  except OSError, e:
    if e.errno != errno.EEXIST:
        raise
  #open desktop file
  text = open(langfile,"r").read()

  # Parse contents and add them to POT
  for mblock in mpattern.findall(text):
    mblock_stripped = mblock.strip('\n')
    message_comment, message_id = mblock.strip('\n').split('=')
    potentry = polib.POEntry(
      msgctxt = message_comment,
      msgid = message_id.decode('utf-8'),
      msgstr = '',
      occurrences=[(langfile,'')]
      )
    if message_id != '':
      try:
	pot.append(potentry)
      except ValueError:
	print 'The entry already exists'
pot.save('po/mageia_desktop.pot')

# Merge translations
for pofile in glob.glob(podir + '/*.po'):
  lang = pofile[:-3].rsplit('/',1)[1]
  pofilename = pofile
  po = polib.pofile(pofilename)
  po.merge(pot)
  po.save(pofilename)

for langfile in files:
  #open desktop file
  deskfile = open(langfile,"r")
  text = deskfile.read()
  deskfile.close()
  deskfile = open(langfile,"w")
  for transblock in tpattern.findall(text):
    text = text.replace(transblock, '')

  # Parse PO files
  for pofile in sorted(glob.glob(podir + '/*.po'), reverse = True):
    lang = pofile[:-3].rsplit('/',1)[1]
    pofilename = pofile
    po = polib.pofile(pofilename)
    for entry in po.translated_entries():
      if entry.msgid.encode('utf-8') in text:
	origmessage = ('\n' + entry.msgctxt + '=' + entry.msgid + '\n').encode('utf-8')
	origandtranslated = ('\n' + entry.msgctxt + '=' + entry.msgid + '\n' + entry.msgctxt + '[' + lang + ']=' + entry.msgstr + '\n').encode('utf-8')
	text = text.replace(origmessage, origandtranslated)

  deskfile.write(text)
  deskfile.close()