properties.html


001| '''Properties Classes.
001| 
001| classes:
001|     Properties              - Properties base class
001|     ApplicationProperties   - name=value pairs (values are all strings)
001|     ObjectProperties        - name=value pairs (values are tuples of tokens)
001|     QueryProperties         - name(value) specifications
001| 
001| Developer@Sonnack.com
001| February 2014
001| '''

002| ####################################################################################################
003| from sys import stderr
004| from lexer import SourceFile, Lexer, LexerLine
005| ####################################################################################################
006| #TODO: ADD Logger
007| 
008| 
009| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
010| class Properties (object):
011|     '''\
011| Properties base class.
011| 
011| properties:
011|     .props          - properties collection
011|     .filename       - properties file name
011| 
011| methods:
011|     [N]             - Nth argument
011|     .len()          - number of arguments
011|     .str()          - string representation
011|     .repr()         - JSON-like representation
011| '''

012|     E1 = "Parser: ERROR *** Oh, No!! There's a Syntax Error! ***"
013|     E2 = "error: %s"
014|     E3 = "file: %s"
015|     E4 = "line: %d, char: %d (chars read: %d)"
016| 
017|     def __init__ (self, filename, LexClass=Lexer):
018|         '''Create a new Properties instance.'''
019|         self.props = {}
020|         self.filename = filename
021|         self.src = SourceFile(self.filename)
022|         self.lex = LexClass(self.src)
023| 
024|     def __iter__ (self):
025|         '''Get Properties Property iterator.'''
026|         return iter(self.props)
027| 
028|     def __len__ (self):
029|         '''Length of an Properties object is number of Property objects.'''
030|         return len(self.props)
031| 
032|     def __getitem__ (self, k):
033|         '''Get Properties Property.'''
034|         return self.props[k]
035| 
036|     def __eq__ (self, other):
037|         '''Compare two Properties objects (using their Source).'''
038|         return (self.src == other.src)
039| 
040|     def keys_sorted_by_name (self):
041|         '''All items sorted by name.'''
042|         return sorted(self.props.keys(), key=lambda k: str(k).lower())
043| 
044|     def items_sorted_by_name (self):
045|         '''All items sorted by name.'''
046|         return sorted(self.props.items(), key=lambda kv: str(kv[0]).lower())
047| 
048|     def _get_tok (self):
049|         '''Get Character.'''
050|         tok = self.lex.get_token()
051|         #print 'token:',tok
052|         return tok
053| 
054|     def _unget_tok (self, tok):
055|         '''Unget Character.'''
056|         self.lex.unget_token(tok)
057| 
058|     def __str__ (self):
059|         '''String version.'''
060|         f = lambda t: '%s: "%s"' % (t[0],str(t[1]))
061|         ss = [f(kv) for kv in self.items_sorted_by_name()]
062|         return '\n'.join(ss)
063| 
064|     def __repr__ (self):
065|         '''JSON-ish version.'''
066|         k = self.keys_sorted_by_name()
067|         s = '{Properties:{len:%d, keys:%s, src:%s, id:%s}}'
068|         t = (len(self), k, repr(self.src), hex(id(self)))
069|         return s % t
070| 
071| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
072| class ApplicationProperties (Properties):
073|     '''\
073| Application Properties Class.
073| 
073| properties:
073| 
073| methods:
073|     [N]             - Nth argument
073|     .len()          - number of arguments
073|     .str()          - string representation
073|     .repr()         - JSON-like representation
073| '''

074|     def __init__ (self, filename):
075|         '''Create a new Application Properties instance.'''
076|         super().__init__(filename, LexerLine)
077|         # Parse file...
078|         try:
079|             self._parse_file()
080|         except IndexError:
081|             pass
082|         except SyntaxError as e:
083|             print(Properties.E1, file=stderr)
084|             print(Properties.E2 % str(e), file=stderr)
085|             print(Properties.E3 % self.src.filename, file=stderr)
086|             print(Properties.E4 % (self.src.lines, self.src.cp, self.src.chars), file=stderr)
087| 
088|     def _parse_file (self):
089|         tok = self._get_tok()
090|         while tok:
091|             # Skip blank lines (and comments)...
092|             if tok[0] == Lexer.NewlineToken:
093|                 tok = self._get_tok()
094|                 continue
095|             # Property name...
096|             if tok[0] not in [Lexer.NameToken, Lexer.StringToken]:
097|                 raise SyntaxError('Expected Property Name. [%s]' % str(tok))
098|             prop_name = tok[1]
099|             # Separator...
100|             tok = self._get_tok()
101|             if tok[0] != Lexer.SymbolToken:
102|                 raise SyntaxError('Expected delimiter. [%s]' % str(tok))
103|             if tok[1] not in [':', '=']:
104|                 raise SyntaxError('Unexpected delimiter. [%s]' % str(tok))
105|             # Value...
106|             ch = self.lex.skip_whitespace()
107|             if ch in self.lex.sdq_chars:
108|                 prop_value = self._get_tok()
109|             else:
110|                 prop_value = self.lex.get_rest_of_line()
111|             # Add Property to collection...
112|             self.props[prop_name] = prop_value[1]
113|             # Continue...
114|             tok = self._get_tok()
115|             ## Loop!! -->>
116| 
117|     def __repr__ (self):
118|         '''JSON-ish version.'''
119|         r = super(ApplicationProperties,self).__repr__()
120|         s = '{ApplicationProperties:{parent:%s, id:%s}}'
121|         t = (r, hex(id(self)))
122|         return s % t
123| 
124| 
125| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
126| class ObjectProperties (Properties):
127|     '''\
127| Object Properties Class.
127| 
127| properties:
127| 
127| methods:
127|     [N]             - Nth argument
127|     .len()          - number of arguments
127|     .str()          - string representation
127|     .repr()         - JSON-like representation
127| '''

128|     def __init__ (self, filename):
129|         '''Create a new Properties instance.'''
130|         super().__init__(filename)
131|         # Parse file...
132|         try:
133|             self._parse_file()
134|         except IndexError:
135|             pass
136|         except SyntaxError as e:
137|             print(Properties.E1, file=stderr)
138|             print(Properties.E2 % str(e), file=stderr)
139|             print(Properties.E3 % self.src.filename, file=stderr)
140|             print(Properties.E4 % (self.src.lines, self.src.cp, self.src.chars), file=stderr)
141| 
142|     def _parse_file (self):
143|         tok = self._get_tok()
144|         while tok:
145|             # Skip blank lines (and comments)...
146|             if tok[0] == Lexer.NewlineToken:
147|                 tok = self._get_tok()
148|                 continue
149|             # Property name...
150|             if tok[0] not in [Lexer.NameToken, Lexer.StringToken]:
151|                 raise SyntaxError('Expected Property Name. [%s]' % str(tok))
152|             prop_name = tok[1]
153|             # Separator...
154|             tok = self._get_tok()
155|             if tok[0] != Lexer.SymbolToken:
156|                 raise SyntaxError('Expected delimiter. [%s]' % str(tok))
157|             if tok[1] not in [':', '=']:
158|                 raise SyntaxError('Unexpected delimiter. [%s]' % str(tok))
159|             # Value...
160|             prop_values = []
161|             tok = self._get_tok()
162|             while tok[0] != Lexer.NewlineToken:
163|                 if tok[0] in [Lexer.NumberToken, Lexer.DateToken]:
164|                     val = tok[2]
165|                 else:
166|                     val = tok[1]
167|                 prop_values.append(val)
168|                 tok = self._get_tok()
169|                 ## Loop!! -->>
170|             # Add Property to collection...
171|             self.props[prop_name] = tuple([len(prop_values)]+prop_values)
172|             # Continue...
173|             tok = self._get_tok()
174|             ## Loop!! -->>
175| 
176|     def __repr__ (self):
177|         '''JSON-ish version.'''
178|         r = super(ObjectProperties,self).__repr__()
179|         s = '{ObjectProperties:{parent:%s, id:%s}}'
180|         t = (r, hex(id(self)))
181|         return s % t
182| 
183| 
184| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
185| class QueryProperties (Properties):
186|     '''\
186| Query Properties Class.
186| 
186| properties:
186|     .text
186|     .args
186| 
186| methods:
186|     [N]             - Nth argument
186|     .len()          - number of arguments
186|     .str()          - string representation
186|     .repr()         - JSON-like representation
186| '''

187|     def __init__ (self, filename):
188|         '''Create a new Properties instance.'''
189|         super().__init__(filename)
190|         # Parse file...
191|         self.lex.nl_flag = False
192|         try:
193|             self._parse_file()
194|         except IndexError:
195|             pass
196|         except SyntaxError as e:
197|             print(Properties.E1, file=stderr)
198|             print(Properties.E2 % str(e), file=stderr)
199|             print(Properties.E3 % self.src.filename, file=stderr)
200|             print(Properties.E4 % (self.src.lines, self.src.cp, self.src.chars), file=stderr)
201| 
202|     def _parse_file (self):
203|         '''| <file> := [<property-name> <property-value>]* |'''
204|         #print 'parse_file:'
205|         tok = self._get_tok()
206|         while tok:
207|             # Expecting a Name Token...
208|             if tok[0] == Lexer.NameToken:
209|                 prop_name = tok[1]
210|                 prop_value = self._parse_prop_value()
211|                 if prop_name not in self.props:
212|                     self.props[prop_name] = [prop_value]
213|                 else:
214|                     self.props[prop_name].append(prop_value)
215|                 # Get next Token and continue...
216|                 tok = self._get_tok()
217|                 continue
218|             # If we get here, the token wasn't recognized...
219|             raise SyntaxError('Unexpected token. [%s]' % str(tok))
220|         # protection!
221|         raise RuntimeError('Unexpected Token loop exit!')
222| 
223|     def _parse_prop_value (self):
224|         '''| <property-value> := "(" <item> [, <item>]* ")" |'''
225|         #print 'parse_prop_value:'
226|         tok = self._get_tok()
227|         while tok:
228|             # Expecting a '(' Token...
229|             if tok[1] == '(':
230|                 # Get Property values (might be empty list)...
231|                 return self._parse_value_list()
232|             #
233|             # If we get here, the token wasn't recognized...
234|             raise SyntaxError('Expected "(" to begin property value! [%s]' % str(tok))
235|         # protection!
236|         raise RuntimeError('Unexpected Token loop exit!')
237| 
238|     def _parse_value_list (self):
239|         '''| <item> ")" or <item> "," |'''
240|         #print 'parse_value_list:'
241|         # Get next Token...
242|         tok = self._get_tok()
243|         # Could be a ')' Token to end the value list...
244|         if tok[1] == ')':
245|             return []
246|         # Got a value, so create value-list...
247|         prop_values = []
248|         while tok:
249|             # Parse the value and add to list...
250|             val = self._parse_value_item(tok)
251|             prop_values.append(val)
252|             # Get next Token...
253|             tok = self._get_tok()
254|             # A comma (',') Token indicates more values...
255|             if tok[1] == ',':
256|                 tok = self._get_tok()
257|                 continue
258|             # A ')' Token indicates end of value(s)...
259|             if tok[1] == ')':
260|                 return prop_values
261|             # If we get here, the token wasn't recognized...
262|             raise SyntaxError('Expected ")" to end property value! [%s]' % str(tok))
263|         # protection!
264|         raise RuntimeError('Unexpected Token loop exit!')
265| 
266|     def _parse_value_item (self, val_tok):
267|         '''| <item> := <constant> or <name> or <sub-property> |'''
268|         #print 'parse_value_item:', val_tok
269|         # Token is Number or Date; add to value list..
270|         if val_tok[0] in [Lexer.NumberToken, Lexer.DateToken]:
271|             return (val_tok[3], val_tok[2])
272|         # Token is String (a little weird, but whatever); add to value list..
273|         if val_tok[0] == Lexer.StringToken:
274|             return ('string', val_tok[1])
275|         # Token is Name; could be a constant or a sub-property..
276|         if val_tok[0] == Lexer.NameToken:
277|             prop_name = val_tok[1]
278|             # Get next Token for sub-property test...
279|             tok = self._get_tok()
280|             # If it has an opening parenthesis, it's a property value...
281|             if tok[1] == '(':
282|                 # Handle sub-property...
283|                 prop_value = self._parse_value_list()
284|                 return ('f:'+prop_name, prop_value)
285|             # Wasn't a sub-property, so UNGET the Token and return the name...
286|             self._unget_tok(tok)
287|             return ('name', prop_name)
288|         # If we get here, the token wasn't recognized...
289|         raise SyntaxError('Expected value token! [%s]' % str(val_tok))
290| 
291|     def __str__ (self):
292|         '''String version.'''
293|         f1 = lambda m: ' %s' % str(m)
294|         f2 = lambda t: '%s:\n%s' % (t[0], '\n'.join([f1(v) for v in t[1]]))
295|         ss = [f2(kv) for kv in self.items_sorted_by_name()]
296|         return ''.join(ss)
297| 
298|     def __repr__ (self):
299|         '''JSON-ish version.'''
300|         r = super(QueryProperties,self).__repr__()
301|         s = '{QueryProperties:{parent:%s, id:%s}}'
302|         t = (r, hex(id(self)))
303|         return s % t
304| 
305| 
306| 
307| ####################################################################################################
308| '''eof'''
309|