Python replacement for java.util.Properties - handles unicode escapes
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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | #! /usr/bin/env python
"""
A Python replacement for java.util.Properties class
Handles Unicode escapes
Preserves comments and order of lines
Created - Anand B Pillai <abpillai@gmail.com>
Updated - Adam Feuer <xxx at pobox.com> (replace xxx with adamf)
"""
import sys,os,codecs
import re
import time
class Properties(object):
""" A Python replacement for java.util.Properties """
def __init__(self, props=None):
self._propertyEntries = {}
self._commentEntries = []
self.equalOrColonSeparatorWithoutBackslashesRe = re.compile(r'(?<!\\)(\s*\=)|(?<!\\)(\s*\:)')
def loadFromString(self, input):
lines = input.split('\n')
self._parse(lines)
def load(self, file):
"""Load properties from an open file stream"""
unicodeFile = codecs.EncodedFile(file, 'latin-1')
try:
lines = unicodeFile.readlines()
unicodeFile.close()
except IOError, e:
raise
self._parse(lines)
def getProperty(self, key):
if self._propertyEntries.has_key(key):
return self._propertyEntries.get(key)["value"]
else:
return ''
def setProperty(self, key, value):
if type(key) is str and type(value) is str:
self._processPair(key, value)
else:
raise TypeError,'both key and value should be strings!'
def propertyNames(self):
return self._propertyEntries.keys()
def getAsString(self):
result = ""
entries = self._propertyEntries.values() + self._commentEntries
entries.sort()
for entry in entries:
if entry["comment"]:
result += "%s\n" % entry["line"]
else:
result += ''.join((entry["key"],'=',entry["value"],'\n'))
return result
def store(self, outFile, header=""):
self._store(outfile, header)
outFile.close()
def _store(self, outFile, header=""):
unicodeOutFile = codecs.EncodedFile(outFile, 'latin-1')
unicodeOutFile.write(header)
unicodeOutFile.write(self.getAsString())
def getPropertyDict(self):
propertyDict = {}
for key, entry in self._propertyEntries.items():
propertyDict[key] = entry["value"]
return propertyDict
def __str__(self):
s='{'
for key,entry in self._propertyEntries.items():
s = ''.join((s,key,'=',entry["value"],', '))
s=''.join((s[:-2],'}'))
return s
def __getitem__(self, name):
""" To support direct dictionary-like access """
return self._propertyEntries[name]["value"]
def __setitem__(self, name, value):
""" To support direct dictionary-like access """
self._processPair(name, value)
def __getattr__(self, name):
"""For attributes not found in self, redirect
to the properties dictionary """
try:
return self.__dict__[name]
except KeyError:
if hasattr(self._propertyEntries, name):
return getattr(self._propertyEntries, name)
else:
raise AttributeError(name)
def _parse(self, lines):
lineIterator = iter(lines)
self.lineNumber = 0
for line in lineIterator:
line = line.strip()
if not line or self._isCommentLine(line):
self._commentEntries.append(self._getPropertyEntry(comment=True, line=line))
else:
indexOfFirstSeparationChar = self._getIndexOfFirstSeparationChar(line)
line = self._joinLinesIfNecessary(line, lineIterator)
key, value = self._splitOnSeparationChar(line, indexOfFirstSeparationChar)
self._processPair(key, value, line)
def _processPair(self, key, value, line=''):
origValue = value
key, origKey = self._removeWhitespaceFromEndOfKey(key)
origValue = self._unescape(origValue)
value = self._unescape(value).strip()
entry = self._getPropertyEntry(key=key, origKey=origKey, value=value, line=line, comment=False)
self._propertyEntries[key] = entry
def _getPropertyEntry(self, **kwargs):
kwargs["lineNumber"] = self.lineNumber
self.lineNumber += 1
return PropertyEntry(**kwargs)
def _getIndexOfFirstSeparationChar(self, line):
indexOfFirstSeparationChar = -1
endPos = self._getEndPositionOfSearch(line)
whiteSpaceSeparatorRe = self._getWhiteSpaceSeparatorRe(line)
if whiteSpaceSeparatorRe.search(line, 0, endPos):
first, last = whiteSpaceSeparatorRe.search(line, 0, endPos).span()
indexOfFirstSeparationChar = first
elif self.equalOrColonSeparatorWithoutBackslashesRe.search(line):
first, last = self.equalOrColonSeparatorWithoutBackslashesRe.search(line).span()
indexOfFirstSeparationChar = last - 1
return indexOfFirstSeparationChar
def _getEndPositionOfSearch(self, line):
matchObj = self.equalOrColonSeparatorWithoutBackslashesRe.search(line)
if matchObj:
first, last = matchObj.span()
return first
else:
return len(line)
def _getWhiteSpaceSeparatorRe(self, line):
whiteSpaceSeparatorRe = re.compile(r'(?<![\\\=\:])(\s)')
if not self.equalOrColonSeparatorWithoutBackslashesRe.search(line):
self.equalOrColonSeparatorRe = re.compile(r'(\s*\=)|(\s*\:)')
if self.equalOrColonSeparatorRe.search(line):
whiteSpaceSeparatorRe = re.compile(r'(?<![\\])(\s)')
return whiteSpaceSeparatorRe
def _joinLinesIfNecessary(self, line, lineIterator):
while line[-1] == '\\':
nextline = lineIterator.next()
nextline = nextline.strip()
line = line[:-1] + nextline
return line
def _splitOnSeparationChar(self, line, indexOfFirstSeparationChar):
if indexOfFirstSeparationChar != -1:
return line[:indexOfFirstSeparationChar], line[indexOfFirstSeparationChar+1:]
else:
return line,''
def _removeWhitespaceFromEndOfKey(self, key):
origKey = key
whitespaceAtEndOfKeyRe = re.compile(r'\\(?!\s$)')
keyparts = whitespaceAtEndOfKeyRe.split(key)
lastpart = keyparts[-1]
if lastpart.find('\\ ') != -1:
keyparts[-1] = lastpart.replace('\\','')
key = ''.join(keyparts)
if lastpart and lastpart[-1] == ' ':
origKey = origKey.strip()
key = key.strip()
return key, origKey
def _escape(self, value):
newvalue = value.replace(':','\:')
newvalue = newvalue.replace('=','\=')
return newvalue
def _unescape(self, value):
newvalue = value.replace('\:',':')
newvalue = newvalue.replace('\=','=')
return newvalue
def _isCommentLine(self, line):
if line[0] == '#': return True
if line[0] == '!': return True
return False
class PropertyEntry(dict):
def __init__(self, **kwargs):
if kwargs is None:
kwargs = {}
dict.__init__(self, kwargs)
def __cmp__(self, other):
return self.getLineNumber() - other.getLineNumber()
def getLineNumber(self):
return self.get("lineNumber", -1)
|
Refactoring of Recipe 496795 with addition of reading and writing of Unicode files (files with Latin-1 encoding, as described here: http://en.wikipedia.org/wiki/.properties
The refactoring was done to make the algorithm clearer and allow addition the unicode feature.
Here's unit tests for the file:
import codecs, unittest, StringIO
import Properties
#
# todo:
# * test writing property files
# * test writing unicode property files
class PropertiesTest(unittest.TestCase):
def setUp(self):
pass
def testPropertiesOneLine(self):
propertiesFile = StringIO.StringIO("foo.bar=baz")
properties = Properties.Properties()
properties.load(propertiesFile)
self.assertEqual("baz", properties["foo.bar"])
def testComments(self):
input = """
#key1=value1
!key1=value1
"""
properties = self.getPropertiesAndLoad(input)
self.assertFalse(properties.has_key("key1"))
self.assertFalse(properties.has_key("#key1"))
self.assertFalse(properties.has_key("!key1"))
def testSeparators(self):
input = """
key2 value2
key3=value3
key4:value4
key5\tvalueA,valueB,valueC
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("value2", properties["key2"])
self.assertEqual("value3", properties["key3"])
self.assertEqual("value4", properties["key4"])
self.assertEqual("valueA,valueB,valueC", properties["key5"])
def testMultilineProperty(self):
input = """
key6 valueD,valueE,valueF, \\
valueG, valueH
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("valueD,valueE,valueF, valueG, valueH", properties["key6"])
def testKeyOnly(self):
input = """
key7
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("", properties["key7"])
def testSpacesInValue(self):
input = """
key8 = valueX valueY valueZ
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("valueX valueY valueZ", properties["key8"])
def testSpacesInKey(self):
input = """
This\\ key= this value
a\\ b\\ c = def
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("this value", properties["This key"])
self.assertEqual("def", properties["a b c"])
def testPropertiesSeveralLines(self):
input = """
#key1=value1
!key1=value1
key2 value2
key3=value3
key4:value4
key5\tvalueA,valueB,valueC
key6 valueD,valueE,valueF, \\
valueG, valueH
key7
key8 = valueX valueY valueZ
This\\ key= this value
"""
properties = self.getPropertiesAndLoad(input)
self.assertFalse(properties.has_key("key1"))
self.assertFalse(properties.has_key("#key1"))
self.assertFalse(properties.has_key("!key1"))
self.assertEqual("value2", properties["key2"])
self.assertEqual("value3", properties["key3"])
self.assertEqual("value4", properties["key4"])
self.assertEqual("valueA,valueB,valueC", properties["key5"])
self.assertEqual("valueD,valueE,valueF, valueG, valueH", properties["key6"])
self.assertEqual("", properties["key7"])
self.assertEqual("valueX valueY valueZ", properties["key8"])
self.assertEqual("this value", properties["This key"])
def testUnicodeValue(self):
expectedValue = u"b\u0061r".encode("latin_1")
key = u"blah.bling".encode("latin_1")
input = key + "=".encode("latin_1") + expectedValue
properties = self.getPropertiesAndLoad(input)
self.assertEqual(expectedValue, properties[key])
def testUnicodeReadFromFile(self):
expectedValue = u"M\u00f6tley Cr\u00fce".encode("latin_1")
key = u"\u0062\u00e2\u00f1\u0064".encode("latin_1")
input = key + "=".encode("latin_1") + expectedValue
file = StringIO.StringIO(input)
properties = Properties.Properties()
properties.load(file)
self.assertEqual(expectedValue, properties[key])
def testUnicodeKeyValue(self):
expectedValue = u"M\u00f6tley Cr\u00fce".encode("latin_1")
key = u"\u0062\u00e2\u00f1\u0064".encode("latin_1")
input = key + "=".encode("latin_1") + expectedValue
properties = self.getPropertiesAndLoad(input)
self.assertEqual(expectedValue, properties[key])
def testUnicode(self):
key = u"\u0061".decode("latin_1")
self.assertTrue("a", key)
def testPropertiesEntry(self):
propertiesEntry = Properties.PropertyEntry()
propertiesEntry["foo"] = "bar"
propertiesEntry["blah"] = "abc"
self.assertEqual("bar", propertiesEntry["foo"])
self.assertEqual("abc", propertiesEntry["blah"])
self.assertEqual("{'blah': 'abc', 'foo': 'bar'}", "%s" % propertiesEntry)
def testPropertiesEntryKeywordInit(self):
propertiesEntry = Properties.PropertyEntry(foo="bar", baz="bling")
self.assertEqual("bar", propertiesEntry["foo"])
self.assertEqual("bling", propertiesEntry["baz"])
def testNewPropsExists(self):
input = """
key3=value3
"""
properties = self.getPropertiesAndLoad(input)
self.assertEqual("value3", properties["key3"])
def testGetAsString(self):
input = """key1=value1
# comment
key2=value2
key3=value3"""
properties = self.getPropertiesAndLoad(input)
expectedValue = "key1=value1\n# comment\nkey2=value2\n\nkey3=value3\n"
actualValue = properties.getAsString()
self.assertEqual(expectedValue, actualValue)
def testStore(self):
input = """key1=value1
# comment
key2=value2
key3=value3"""
properties = self.getPropertiesAndLoad(input)
expectedValue = "key1=value1\n# comment\nkey2=value2\n\nkey3=value3\n"
outputFile = StringIO.StringIO(u"")
self.assertEqual("", outputFile.getvalue())
properties._store(outputFile)
self.assertEqual(expectedValue, outputFile.getvalue())
def testGetPropertyDict(self):
input = """key1=value1
key2=value2
key3=value3"""
properties = self.getPropertiesAndLoad(input)
expectedValue = {"key1" : "value1", "key2" : "value2", "key3" : "value3"}
self.assertEqual(expectedValue, properties.getPropertyDict())
def getPropertiesAndLoad(self, input):
properties = Properties.Properties()
properties.loadFromString(input)
return properties
if __name__ == '__main__':
unittest.main()
Tags: files