fix git support for v1.5.3 (or higher) by setting "--work-tree"
[translate_toolkit.git] / storage / ts.py
blob76d142cd67a4a8bd0822f557c3dfd270672fe9cf
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # Copyright 2004-2007 Zuza Software Foundation
5 #
6 # This file is part of translate.
8 # translate is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # translate is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with translate; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 """Module for parsing Qt .ts files for translation.
25 Currently this module supports the old format of .ts files. Some applictaions
26 use the newer .ts format which are documented here:
27 U{TS file format 4.3<http://doc.trolltech.com/4.3/linguist-ts-file-format.html>},
28 U{Example<http://svn.ez.no/svn/ezcomponents/trunk/Translation/docs/linguist-format.txt>}
30 U{Specification of the valid variable entries <http://doc.trolltech.com/4.3/qstring.html#arg>},
31 U{2 <http://doc.trolltech.com/4.3/qstring.html#arg-2>}
32 """
34 from translate.misc import ourdom
36 class QtTsParser:
37 contextancestors = dict.fromkeys(["TS"])
38 messageancestors = dict.fromkeys(["TS", "context"])
39 def __init__(self, inputfile=None):
40 """make a new QtTsParser, reading from the given inputfile if required"""
41 self.filename = getattr(inputfile, "filename", None)
42 self.knowncontextnodes = {}
43 self.indexcontextnodes = {}
44 if inputfile is None:
45 self.document = ourdom.parseString("<!DOCTYPE TS><TS></TS>")
46 else:
47 self.document = ourdom.parse(inputfile)
48 assert self.document.documentElement.tagName == "TS"
50 def addtranslation(self, contextname, source, translation, comment=None, transtype=None, createifmissing=False):
51 """adds the given translation (will create the nodes required if asked). Returns success"""
52 contextnode = self.getcontextnode(contextname)
53 if contextnode is None:
54 if not createifmissing:
55 return False
56 # construct a context node with the given name
57 contextnode = self.document.createElement("context")
58 namenode = self.document.createElement("name")
59 nametext = self.document.createTextNode(contextname)
60 namenode.appendChild(nametext)
61 contextnode.appendChild(namenode)
62 self.document.documentElement.appendChild(contextnode)
63 if not createifmissing:
64 return False
65 messagenode = self.document.createElement("message")
66 sourcenode = self.document.createElement("source")
67 sourcetext = self.document.createTextNode(source)
68 sourcenode.appendChild(sourcetext)
69 messagenode.appendChild(sourcenode)
70 if comment:
71 commentnode = self.document.createElement("comment")
72 commenttext = self.document.createTextNode(comment)
73 commentnode.appendChild(commenttext)
74 messagenode.appendChild(commentnode)
75 translationnode = self.document.createElement("translation")
76 translationtext = self.document.createTextNode(translation)
77 translationnode.appendChild(translationtext)
78 if transtype:
79 translationnode.setAttribute("type", transtype)
80 messagenode.appendChild(translationnode)
81 contextnode.appendChild(messagenode)
82 return True
84 def getxml(self):
85 """return the ts file as xml"""
86 xml = self.document.toprettyxml(indent=" ", encoding="utf-8")
87 #This line causes empty lines in the translation text to be removed (when there are two newlines)
88 xml = "\n".join([line for line in xml.split("\n") if line.strip()])
89 return xml
91 def getcontextname(self, contextnode):
92 """returns the name of the given context"""
93 namenode = ourdom.getFirstElementByTagName(contextnode, "name")
94 return ourdom.getnodetext(namenode)
96 def getcontextnode(self, contextname):
97 """finds the contextnode with the given name"""
98 contextnode = self.knowncontextnodes.get(contextname, None)
99 if contextnode is not None:
100 return contextnode
101 contextnodes = self.document.searchElementsByTagName("context", self.contextancestors)
102 for contextnode in contextnodes:
103 if self.getcontextname(contextnode) == contextname:
104 self.knowncontextnodes[contextname] = contextnode
105 return contextnode
106 return None
108 def getmessagenodes(self, context=None):
109 """returns all the messagenodes, limiting to the given context (name or node) if given"""
110 if context is None:
111 return self.document.searchElementsByTagName("message", self.messageancestors)
112 else:
113 if isinstance(context, (str, unicode)):
114 # look up the context node by name
115 context = self.getcontextnode(context)
116 if context is None:
117 return []
118 return context.searchElementsByTagName("message", self.messageancestors)
120 def getmessagesource(self, message):
121 """returns the message source for a given node"""
122 sourcenode = ourdom.getFirstElementByTagName(message, "source")
123 return ourdom.getnodetext(sourcenode)
125 def getmessagetranslation(self, message):
126 """returns the message translation for a given node"""
127 translationnode = ourdom.getFirstElementByTagName(message, "translation")
128 return ourdom.getnodetext(translationnode)
130 def getmessagetype(self, message):
131 """returns the message translation attributes for a given node"""
132 translationnode = ourdom.getFirstElementByTagName(message, "translation")
133 return translationnode.getAttribute("type")
135 def getmessagecomment(self, message):
136 """returns the message comment for a given node"""
137 commentnode = ourdom.getFirstElementByTagName(message, "comment")
138 # NOTE: handles only one comment per msgid (OK)
139 # and only one-line comments (can be VERY wrong) TODO!!!
140 return ourdom.getnodetext(commentnode)
142 def iteritems(self):
143 """iterates through (contextname, messages)"""
144 for contextnode in self.document.searchElementsByTagName("context", self.contextancestors):
145 yield self.getcontextname(contextnode), self.getmessagenodes(contextnode)
147 def __del__(self):
148 """clean up the document if required"""
149 if hasattr(self, "document"):
150 self.document.unlink()