bloodhound-mq / t115 / t115_r1427886_product_config.diff

The branch 't115_product_env' does not exist.
  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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# HG changeset patch
# Parent beed3d3bb95c8439bd31a7a68840c036e5f1a29c
BH Multiproduct #115 : Product-specific settings

diff -r beed3d3bb95c bloodhound_dashboard/bhdashboard/model.py
--- a/bloodhound_dashboard/bhdashboard/model.py	Mon Jan 07 13:44:27 2013 -0500
+++ b/bloodhound_dashboard/bhdashboard/model.py	Mon Jan 07 22:58:47 2013 -0500
@@ -117,8 +117,9 @@
                 self._update_from_row(row)
                 break
             else:
-                raise ResourceNotFound('No %(object_name)s with %(where)s' %
-                                sdata)
+                raise ResourceNotFound(
+                        ('No %(object_name)s with %(where)s' % sdata) 
+                                % tuple(values))
     
     def delete(self):
         """Deletes the matching record from the database"""
@@ -144,14 +145,15 @@
                                       for k in self._meta['key_fields']]))):
             sdata = {'keys':','.join(["%s='%s'" % (k, self._data[k])
                                      for k in self._meta['key_fields']])}
-        elif len(self.select(self._env, where =
+        elif self._meta['unique_fields'] and len(self.select(self._env, where =
                                 dict([(k,self._data[k])
                                       for k in self._meta['unique_fields']]))):
             sdata = {'keys':','.join(["%s='%s'" % (k, self._data[k])
                                      for k in self._meta['unique_fields']])}
         if sdata:
             sdata.update(self._meta)
-            raise TracError('%(object_name)s %(keys)s already exists' %
+            sdata['values'] = self._data
+            raise TracError('%(object_name)s %(keys)s already exists %(values)s' %
                             sdata)
             
         for key in self._meta['key_fields']:
@@ -207,7 +209,7 @@
             TicketSystem(self._env).reset_ticket_fields()
     
     @classmethod
-    def select(cls, env, db=None, where=None):
+    def select(cls, env, db=None, where=None, limit=None):
         """Query the database to get a set of records back"""
         rows = []
         fields = cls._meta['key_fields']+cls._meta['non_key_fields']
@@ -218,7 +220,11 @@
         wherestr, values = dict_to_kv_str(where)
         if wherestr:
             wherestr = ' WHERE ' + wherestr
-        for row in env.db_query(sql + wherestr, values):
+        if limit is not None:
+            limitstr = ' LIMIT ' + str(int(limit))
+        else:
+            limitstr = ''
+        for row in env.db_query(sql + wherestr + limitstr, values):
             # we won't know which class we need until called
             model = cls.__new__(cls)
             data = dict([(fields[i], row[i]) for i in range(len(fields))])
diff -r beed3d3bb95c bloodhound_multiproduct/multiproduct/api.py
--- a/bloodhound_multiproduct/multiproduct/api.py	Mon Jan 07 13:44:27 2013 -0500
+++ b/bloodhound_multiproduct/multiproduct/api.py	Mon Jan 07 22:58:47 2013 -0500
@@ -31,9 +31,9 @@
 from trac.util.translation import _, N_
 from trac.web.chrome import ITemplateProvider
 
-from multiproduct.model import Product, ProductResourceMap
+from multiproduct.model import Product, ProductResourceMap, ProductSetting
 
-DB_VERSION = 2
+DB_VERSION = 3
 DB_SYSTEM_KEY = 'bloodhound_multi_product_version'
 PLUGIN_NAME = 'Bloodhound multi product'
 
@@ -44,7 +44,7 @@
             IPermissionRequestor, ITicketFieldProvider, IResourceManager)
     
     SCHEMA = [modelcls._get_schema() \
-                for modelcls in (Product, ProductResourceMap)]
+                for modelcls in (Product, ProductResourceMap, ProductSetting)]
     del modelcls
     
     def get_version(self):
diff -r beed3d3bb95c bloodhound_multiproduct/multiproduct/config.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bloodhound_multiproduct/multiproduct/config.py	Mon Jan 07 22:58:47 2013 -0500
@@ -0,0 +1,291 @@
+
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing,
+#  software distributed under the License is distributed on an
+#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#  KIND, either express or implied.  See the License for the
+#  specific language governing permissions and limitations
+#  under the License.
+
+"""Configuration objects for Bloodhound product environments"""
+
+__all__ = 'Configuration', 'Section'
+
+import os.path
+
+from trac.config import Configuration, ConfigurationError, Option, Section, \
+        _use_default
+from trac.resource import ResourceNotFound
+from trac.util.text import to_unicode
+
+from multiproduct.model import ProductSetting
+
+class Configuration(Configuration):
+    """Product-aware settings repository equivalent to instances of
+    `trac.config.Configuration` (and thus `ConfigParser` from the
+    Python Standard Library) but retrieving configuration values 
+    from the database.
+    """
+    def __init__(self, env, product, parents=None):
+        """Initialize configuration object with an instance of 
+        `trac.env.Environment` and product prefix.
+
+        Optionally it is possible to inherit settings from parent
+        Configuration objects. Environment's configuration will not
+        be added to parents list.
+        """
+        self.env = env
+        self.parents = (parents or [])
+        self.product = to_unicode(product)
+        self._sections = {}
+
+    def __getitem__(self, name):
+        """Return the configuration section with the specified name.
+        """
+        if name not in self._sections:
+            self._sections[name] = Section(self, name)
+        return self._sections[name]
+
+    def sections(self, compmgr=None, defaults=True):
+        """Return a list of section names.
+
+        If `compmgr` is specified, only the section names corresponding to
+        options declared in components that are enabled in the given
+        `ComponentManager` are returned.
+        """
+        sections = set(to_unicode(s) \
+                for s in ProductSetting.get_sections(self.env, self.product))
+        for parent in self.parents:
+            sections.update(parent.sections(compmgr, defaults=False))
+        if defaults:
+            sections.update(self.defaults(compmgr))
+        return sorted(sections)
+
+    def has_option(self, section, option, defaults=True):
+        """Returns True if option exists in section in either the project
+        trac.ini or one of the parents, or is available through the Option
+        registry.
+
+        (since Trac 0.11)
+        """
+        if ProductSetting.exists(self.env, self.product, section, option):
+            return True
+        for parent in self.parents:
+            if parent.has_option(section, option, defaults=False):
+                return True
+        return defaults and (section, option) in Option.registry
+
+    def save(self):
+        """Nothing to do.
+
+        Notice: Opposite to Trac's Configuration objects Bloodhound's
+        product configuration objects commit changes to the database 
+        immediately. Thus there's no much to do in this method.
+        """
+
+    def parse_if_needed(self, force=False):
+        """Just invalidate options cache.
+
+        Notice: Opposite to Trac's Configuration objects Bloodhound's
+        product configuration objects commit changes to the database 
+        immediately. Thus there's no much to do in this method.
+        """
+        for section in self.sections():
+            self[section]._cache.clear()
+
+    def touch(self):
+        pass
+
+    def set_defaults(self, compmgr=None):
+        """Retrieve all default values and store them explicitly in the
+        configuration, so that they can be saved to file.
+
+        Values already set in the configuration are not overridden.
+        """
+        for section, default_options in self.defaults(compmgr).items():
+            for name, value in default_options.items():
+                if not ProductSetting.exists(self.env, self.product,
+                        section, name):
+                    if any(parent[section].contains(name, defaults=False)
+                           for parent in self.parents):
+                        value = None
+                    self.set(section, name, value)
+
+class Section(Section):
+    """Proxy for a specific configuration section.
+
+    Objects of this class should not be instantiated directly.
+    """
+    __slots__ = ['config', 'name', 'overridden', '_cache']
+
+    def __init__(self, config, name):
+        self.config = config
+        self.name = to_unicode(name)
+        self.overridden = {}
+        self._cache = {}
+
+    @property
+    def env(self):
+        return self.config.env
+
+    @property
+    def product(self):
+        return self.config.product
+
+    def contains(self, key, defaults=True):
+        key = to_unicode(key)
+        if ProductSetting.exists(self.env, self.product, self.name, key):
+            return True
+        for parent in self.config.parents:
+            if parent[self.name].contains(key, defaults=False):
+                return True
+        return defaults and Option.registry.has_key((self.name, key))
+
+    __contains__ = contains
+
+    def iterate(self, compmgr=None, defaults=True):
+        """Iterate over the options in this section.
+
+        If `compmgr` is specified, only return default option values for
+        components that are enabled in the given `ComponentManager`.
+        """
+        options = set()
+        name_str = self.name
+        for setting in ProductSetting.select(self.env,
+                where={'product':self.product, 'section':name_str}):
+            option = to_unicode(setting.option)
+            options.add(option.lower())
+            yield option
+        for parent in self.config.parents:
+            for option in parent[self.name].iterate(defaults=False):
+                loption = option.lower()
+                if loption not in options:
+                    options.add(loption)
+                    yield option
+        if defaults:
+            for section, option in Option.get_registry(compmgr).keys():
+                if section == self.name and option.lower() not in options:
+                    yield option
+
+    __iter__ = iterate
+
+    def __repr__(self):
+        return '<%s [%s , %s]>' % (self.__class__.__name__, \
+                self.product, self.name)
+
+    def get(self, key, default=''):
+        """Return the value of the specified option.
+
+        Valid default input is a string. Returns a string.
+        """
+        cached = self._cache.get(key, _use_default)
+        if cached is not _use_default:
+            return cached
+        name_str = self.name
+        key_str = to_unicode(key)
+        settings = ProductSetting.select(self.env, 
+                where={'product':self.product, 'section':name_str,
+                        'option':key_str})
+        if len(settings) > 0:
+            value = settings[0].value
+        else:
+            for parent in self.config.parents:
+                value = parent[self.name].get(key, _use_default)
+                if value is not _use_default:
+                    break
+            else:
+                if default is not _use_default:
+                    option = Option.registry.get((self.name, key))
+                    value = option.default if option else _use_default
+                else:
+                    value = _use_default
+        if value is _use_default:
+            return default
+        if not value:
+            value = u''
+        elif isinstance(value, basestring):
+            value = to_unicode(value)
+        self._cache[key] = value
+        return value
+
+    def getpath(self, key, default=''):
+        """Return a configuration value as an absolute path.
+
+        Relative paths are resolved relative to `conf` subfolder 
+        of the target global environment. This approach is consistent
+        with TracIni path resolution.
+
+        Valid default input is a string. Returns a normalized path.
+
+        (enabled since Trac 0.11.5)
+        """
+        path = self.get(key, default)
+        if not path:
+            return default
+        if not os.path.isabs(path):
+            path = os.path.join(self.env.path, 'conf', path)
+        return os.path.normcase(os.path.realpath(path))
+
+    def remove(self, key):
+        """Delete a key from this section.
+
+        Like for `set()`, the changes won't persist until `save()` gets called.
+        """
+        key_str = to_unicode(key)
+        option_key = {
+                'product' : self.product, 
+                'section' : self.name,
+                'option' : key_str,
+            }
+        try:
+            setting = ProductSetting(self.env, keys=option_key)
+        except ResourceNotFound:
+            self.env.log.warning("No record for product option %s", option_key)
+        else:
+            self._cache.pop(key, None)
+            setting.delete()
+            self.env.log.info("Removing product option %s", option_key)
+
+    def set(self, key, value):
+        """Change a configuration value.
+
+        These changes will be persistent right away.
+        """
+        key_str = to_unicode(key)
+        value_str = to_unicode(value)
+        self._cache.pop(key_str, None)
+        option_key = {
+                'product' : self.product, 
+                'section' : self.name,
+                'option' : key_str,
+            }
+        try:
+            setting = ProductSetting(self.env, option_key)
+        except ResourceNotFound:
+            if value is not None:
+                # Insert new record in the database
+                setting = ProductSetting(self.env)
+                setting._data.update(option_key)
+                setting._data['value'] = value_str
+                self.env.log.debug('Writing option %s', setting._data)
+                setting.insert()
+        else:
+            if value is None:
+                # Delete existing record from the database
+                # FIXME : Why bother with setting overriden
+                self.overridden[key] = True
+                setting.delete()
+            else:
+                # Update existing record
+                setting.value = value
+                setting.update()
+
diff -r beed3d3bb95c bloodhound_multiproduct/multiproduct/model.py
--- a/bloodhound_multiproduct/multiproduct/model.py	Mon Jan 07 13:44:27 2013 -0500
+++ b/bloodhound_multiproduct/multiproduct/model.py	Mon Jan 07 22:58:47 2013 -0500
@@ -18,6 +18,7 @@
 
 """Models to support multi-product"""
 from datetime import datetime
+from itertools import izip
 
 from trac.core import TracError
 from trac.resource import Resource
@@ -27,6 +28,10 @@
 
 from bhdashboard.model import ModelBase
 
+# -------------------------------------------
+# Product API
+# -------------------------------------------
+
 
 class Product(ModelBase):
     """The Product table"""
@@ -37,12 +42,12 @@
             'no_change_fields':['prefix',],
             'unique_fields':['name'],
             }
-    
+
     @property
     def resource(self):
         """Allow Product to be treated as a Resource"""
         return Resource('product', self.prefix)
-    
+
     def delete(self, resources_to=None):
         """ override the delete method so that we can move references to this
         object to a new product """
@@ -59,7 +64,7 @@
         for prm in ProductResourceMap.select(self._env, where=where):
             prm._data['product_id'] = resources_to
             prm.update()
-    
+
     def _update_relations(self, db=None, author=None):
         """Extra actions due to update"""
         # tickets need to be updated
@@ -71,7 +76,7 @@
             for t in Product.get_tickets(self._env, self._data['prefix']):
                 ticket = Ticket(self._env, t['id'], db)
                 ticket.save_changes(author, comment, now)
-    
+
     @classmethod
     def get_tickets(cls, env, product=''):
         """Retrieve all tickets associated with the product."""
@@ -88,7 +93,7 @@
             'unique_fields':[],
             'auto_inc':['id'],
             }
-    
+
     def reparent_resource(self, product=None):
         """a specific function to update a record when it is to move product"""
         if product is not None:
@@ -101,3 +106,39 @@
         self._data['product_id'] = product
         self.update()
 
+# -------------------------------------------
+# Configuration
+# -------------------------------------------
+
+class ProductSetting(ModelBase):
+    """The Product configuration table
+    """
+    _meta = {'table_name':'bloodhound_productconfig',
+            'object_name':'ProductSetting',
+            'key_fields':['product', 'section', 'option'],
+            'non_key_fields':['value', ],
+            'no_change_fields':['product', 'section', 'option'],
+            'unique_fields':[],
+            }
+
+    @classmethod
+    def exists(cls, env, product, section=None, option=None, db=None):
+        """Determine whether there are configuration values for
+        product, section, option .
+        """
+        if product is None:
+            raise ValueError("Product prefix required")
+        l = locals()
+        option_subkey = ([c, l[c]] for c in ('product', 'section', 'option'))
+        option_subkey = dict(c for c in option_subkey if c[1] is not None)
+        return len(cls.select(env, db, where=option_subkey, limit=1)) > 0
+
+    @classmethod
+    def get_sections(cls, env, product):
+        """Retrieve configuration sections defined for a product
+        """
+        # FIXME: Maybe something more ORM-ish should be added in ModelBase
+        return [row[0] for row in env.db_query("""SELECT DISTINCT section 
+                FROM bloodhound_productconfig WHERE product = %s""", 
+                (product,)) ]
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.