for git v1.5.2 (and below): chdir to the directory of the target file before executin...
[translate_toolkit.git] / misc / autoencode.py
blob37786dee03a1457b65a43b899e18d071c95e112a
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2006 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
22 """Supports a hybrid Unicode string that knows which encoding is preferable,
23 and uses this when converting to a string."""
25 class autoencode(unicode):
26 def __new__(newtype, string=u"", encoding=None, errors=None):
27 if isinstance(string, unicode):
28 if errors is None:
29 newstring = unicode.__new__(newtype, string)
30 else:
31 newstring = unicode.__new__(newtype, string, errors=errors)
32 if encoding is None and isinstance(string, autoencode):
33 newstring.encoding = string.encoding
34 else:
35 newstring.encoding = encoding
36 else:
37 if errors is None and encoding is None:
38 newstring = unicode.__new__(newtype, string)
39 elif errors is None:
40 try:
41 newstring = unicode.__new__(newtype, string, encoding)
42 except LookupError, e:
43 raise ValueError(str(e))
44 elif encoding is None:
45 newstring = unicode.__new__(newtype, string, errors)
46 else:
47 newstring = unicode.__new__(newtype, string, encoding, errors)
48 newstring.encoding = encoding
49 return newstring
51 def join(self, seq):
52 return autoencode(super(autoencode, self).join(seq))
54 def __str__(self):
55 if self.encoding is None:
56 return super(autoencode, self).__str__()
57 else:
58 return self.encode(self.encoding)